Click here to Skip to main content
6,295,667 members and growing! (17,392 online)
Email Password   helpLost your password?
Database » Database » General     Intermediate

Load/Unload images into/from DB table

By Maxim Alekseykin

Explains how to load a BLOB data into a DB table and how to get it from the DB table.
C#, SQL.NET 1.1, Win2K, WinXP, Win2003, VistaSQL 2000, VS.NET2003, DBA, Dev
Posted:17 Jan 2005
Updated:24 Aug 2005
Views:125,851
Bookmarked:87 times
Announcements
Loading...
 
Search    
Advanced Search
printPrint   Broken Article?Report       add Share
  Discuss Discuss   Recommend Article Email
21 votes for this article.
Popularity: 4.81 Rating: 3.64 out of 5
1 vote, 4.8%
1
2 votes, 9.5%
2
1 vote, 4.8%
3
8 votes, 38.1%
4
9 votes, 42.9%
5

Sample Image - imageStorage.jpg

Introduction

We all often need to store Binary Large Objects (BLOBs) 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.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Maxim Alekseykin


Member
MCAD

Now is looking for remote job.

- C++/C#, VB/VBA, SQL Server/Access databases.
- automatic testing, code review
- performance tuning
max.uk2005@gmail.com
-
Occupation: Team Leader
Location: Russian Federation Russian Federation

Other popular Database articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 25 of 25 (Total in Forum: 25) (Refresh)FirstPrevNext
GeneralСпасибо! Pinmemberskiner12:51 13 Oct '08  
GeneralExample with SQL Server Pinmembermayurmv18:21 5 Sep '08  
GeneralSave an Image to SQL2000 server using OLEDB connection Pinmembermahalirajesh18:13 13 Mar '07  
GeneralHelp reagarding inserting Image in Oracle Databse using OLEDB Pinmemberrupangupta4:07 28 Jul '06  
GeneralHelp reagarding inserting Image in Oracle Databse using OLEDB Pinmemberrupangupta3:49 28 Jul '06  
GeneralThe Code for VB.net Pinmembernazrulislam3:15 21 Jul '06  
GeneralRe: The Code for VB.net PinmemberMaxim Alekseikin7:09 21 Jul '06  
QuestionError Saving the Image Pinmembermig1611:23 6 Mar '06  
AnswerRe: Error Saving the Image Pinmembermig1611:37 6 Mar '06  
GeneralRe: Error Saving the Image Pinmembermaziarm11:08 29 May '07  
GeneralSHow image .net PinmemberHanieef21:44 27 Feb '06  
GeneralOne problem... PinsussAntonio Dias11:06 31 Aug '05  
GeneralRe: One problem... PinmemberLev Vayner.9:51 5 Oct '07  
Generalwhy does it has error when running? Pinmemberuumeme4:03 12 Aug '05  
GeneralRe: why does it has error when running? PinsussAnonymous5:08 12 Aug '05  
GeneralRe: why does it has error when running? Pinmemberuumeme20:05 16 Aug '05  
GeneralRe: why does it has error when running? PinmemberMaxim Alekseikin5:35 18 Aug '05  
GeneralThank! PinmemberJaimirG6:48 20 Jun '05  
GeneralLoad Pinmemberrm_babar21:40 28 Apr '05  
GeneralError Pinmemberlyptus12:53 23 Feb '05  
GeneralRe: Error Pinmemberlyptus12:57 23 Feb '05  
GeneralRe: Error PinmemberMaxim Alekseikin, MCAD5:00 24 Feb '05  
GeneralGood simple artcile PinmemberNirosh17:41 9 Feb '05  
GeneralRe: Good simple artcile PinmemberMaxim Alekseikin, MCAD1:18 22 Feb '05  
GeneralRe: Good simple artcile PinmemberNirosh3:34 1 Nov '06  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 24 Aug 2005
Editor: Smitha Vijayan
Copyright 2005 by Maxim Alekseykin
Everything else Copyright © CodeProject, 1999-2009
Web16 | Advertise on the Code Project