SQL Server 2000Windows VistaDBAVisual Studio .NET 2003Windows 2003.NET 1.1Windows 2000Windows XPIntermediateDevVisual StudioSQL ServerSQLWindows.NETC#
Load/Unload images into/from DB table






3.88/5 (25 votes)
Jan 17, 2005

221034

3510
Explains how to load a BLOB data into a DB table and how to get it from the DB table.
Introduction
We all often need to store Binary Large Objects (BLOB
s) into a DB table and then get them from there. Now I'm going to explain the easiest way to do this.
Prepare Database
Run SQL Server Enterprise Manager and create a new database, call it 'Test'. Create a new table and call it Images.
CREATE TABLE Images ([stream] [image] NULL)
That's all you need.
Store Image into DB table
...
byte[] content = ReadBitmap2ByteArray(fileName);
StoreBlob2DataBase(content);
...
protected static byte[] ReadBitmap2ByteArray(string fileName)
{
using(Bitmap image = new Bitmap(fileName))
{
MemoryStream stream = new MemoryStream();
image.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp);
return stream.ToArray();
}
}
protected static void StoreBlob2DataBase(byte[] content)
{
SqlConnection con = Connection;
con.Open();
try
{
// insert new entry into table
SqlCommand insert = new SqlCommand(
"insert into Images ([stream]) values (@image)",con);
SqlParameter imageParameter =
insert.Parameters.Add("@image", SqlDbType.Binary);
imageParameter.Value = content;
imageParameter.Size = content.Length;
insert.ExecuteNonQuery();
}
finally
{
con.Close();
}
}
Store Images for OLEDB provider
Some of us use OLEDB provider to communicate with SQL Server. In this case you should use the code below to store images into your DB. Pay attention to using '?
' instead of '@image
' in the SQL query.
protected static void StoreBlob2DataBaseOleDb(byte[] content)
{
try
{
using(OleDbConnection con = Connection)
{
con.Open();
// insert new entry into table
using(OleDbCommand insert = new OleDbCommand(
"insert into Images ([stream]) values (?)",con))
{
OleDbParameter imageParameter =
insert.Parameters.Add("@image", OleDbType.Binary);
imageParameter.Value = content;
imageParameter.Size = content.Length;
insert.ExecuteNonQuery();
}
}
}
catch(Exception ex)
{
// some exception processing
}
}
Get Image from DB table and show it
// get image
DataRowView drv = (DataRowView) _cm.Current;
byte[] content = (byte[])drv["stream"];
MemoryStream stream = new MemoryStream(content);
Bitmap image = new Bitmap(stream);
ShowImageForm f = new ShowImageForm();
f._viewer.Image = image;
f.ShowDialog(this);
Conclusion
You can use this technique to work with any type of binary data without using storage procedures. Good Luck.