Introduction
This sample code explains how you can store images in a SQL Server database. It uses ADO.NET System.Data.SqlClient
namespace. Images can be stored in SQL server using SQL parameters.
How to Store Images in SQL Server Table
To store an image into SQL Server, you need to read an image file into a byte array. Once you have image data in a byte array, you can easily store this image data in SQL Server using SQL parameters. The following code explains how to do this:
private void cmdSave_Click(object sender, EventArgs e)
{
try
{
byte[] imageData = ReadFile(txtImagePath.Text);
SqlConnection CN = new SqlConnection(txtConnectionString.Text);
string qry = "insert into ImagesStore
(OriginalPath,ImageData) values(@OriginalPath, @ImageData)";
SqlCommand SqlCom = new SqlCommand(qry, CN);
SqlCom.Parameters.Add(new SqlParameter("@OriginalPath",
(object)txtImagePath.Text));
SqlCom.Parameters.Add(new SqlParameter("@ImageData", (object)imageData));
CN.Open();
SqlCom.ExecuteNonQuery();
CN.Close();
this.Close();
}
The following code explains how to read an image file into a byte array:
byte[] ReadFile(string sPath)
{
byte[] data = null;
FileInfo fInfo = new FileInfo(sPath);
long numBytes = fInfo.Length;
FileStream fStream = new FileStream(sPath, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fStream);
data = br.ReadBytes((int)numBytes);
return data;
}
How to Read Image Data from SQL Server Table
To read images from SQL Server, prepare a dataset first which will hold data from SQL Server table. Bind this dataset
with a gridview
control on form.
void GetImagesFromDatabase()
{
try
{
SqlConnection CN = new SqlConnection(txtConnectionString.Text);
SqlDataAdapter ADAP = new SqlDataAdapter("Select * from ImagesStore", CN);
DataSet DS = new DataSet();
ADAP.Fill(DS, "ImagesStore");
dataGridView1.DataSource = DS.Tables["ImagesStore"];
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
Once you have image data in the grid, get image data from grid cell. Alternatively you can also get image data from Dataset
table cell.
private void dataGridView1_CellEnter(object sender, DataGridViewCellEventArgs e)
{
try
{
byte[] imageData =
(byte[])dataGridView1.Rows[e.RowIndex].Cells["ImageData"].Value;
Image newImage;
using (MemoryStream ms = new MemoryStream(imageData, 0, imageData.Length))
{
ms.Write(imageData, 0, imageData.Length);
newImage = Image.FromStream(ms, true);
}
pictureBox1.Image = newImage;
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
If you want, you can extend this code to save image from PictureBox to a local image file.
pictureBox1.Image.Save("c:\test_picture.jpg",System.Drawing.Imaging.ImageFormat.Jpeg);
Points of Interest
If you see frmImageStore
in design mode, I have placed picturebox1
into a panel
. This panel's AutoScroll
property is set to True
and SizeMode
property of PictureBox1
is set to True
. This allows picturebox
to resize itself to the size of the original picture. When picturebox
's size is more than Panel1
's size, scrollbars becomes active for Panel
.
How to Download and Run the Program
- Download the source zip from my website http://www.shabdar.org and extract it.
- Restore the database from SQL Database folder.
- If somehow you cannot restore the provided database, you can generate the necessary table using the script provided in SQL Database directory.
- Open the solution and change connection string on
frmImagesStore
form.
Requirements
- Visual Studio .NET 2005
- .NET Framework 2.0
- Microsoft SQL Server 2000 database or Microsoft SQL Server 2005 database