Click here to Skip to main content
Licence 
First Posted 16 Jan 2005
Views 161,456
Bookmarked 103 times

Load/Unload images into/from DB table

By | 23 Aug 2005 | Article
Explains how to load a BLOB data into a DB table and how to get it from the DB table.
 
Part of The SQL Zone sponsored by
See Also

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

Team Leader

Russian Federation Russian Federation

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
-

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
QuestionThis simple solution to stuffing image data in an SQL database compiles @ VS2010 PinmemberRedDK8:15 29 Sep '11  
GeneralMy vote of 4 PinmemberAmir Mehrabi-Jorshary2:27 23 Jul '10  
GeneralСпасибо! Pinmemberskiner11:51 13 Oct '08  
GeneralExample with SQL Server Pinmembermayurmv17:21 5 Sep '08  
GeneralSave an Image to SQL2000 server using OLEDB connection Pinmembermahalirajesh17:13 13 Mar '07  
GeneralHelp reagarding inserting Image in Oracle Databse using OLEDB Pinmemberrupangupta3:07 28 Jul '06  
GeneralHelp reagarding inserting Image in Oracle Databse using OLEDB Pinmemberrupangupta2:49 28 Jul '06  
GeneralThe Code for VB.net Pinmembernazrulislam2:15 21 Jul '06  
I want to stor image in to Oracle Database Using VB.net. Please Help me......
GeneralRe: The Code for VB.net PinmemberMaxim Alekseikin6:09 21 Jul '06  
GeneralRe: The Code for VB.net Pinmembertorabis874:24 4 Aug '09  
QuestionError Saving the Image Pinmembermig1610:23 6 Mar '06  
AnswerRe: Error Saving the Image Pinmembermig1610:37 6 Mar '06  
GeneralRe: Error Saving the Image Pinmembermaziarm10:08 29 May '07  
GeneralSHow image .net PinmemberHanieef20:44 27 Feb '06  
GeneralOne problem... PinsussAntonio Dias10:06 31 Aug '05  
GeneralRe: One problem... PinmemberLev Vayner.8:51 5 Oct '07  
Questionwhy does it has error when running? Pinmemberuumeme3:03 12 Aug '05  
AnswerRe: why does it has error when running? PinsussAnonymous4:08 12 Aug '05  
GeneralRe: why does it has error when running? Pinmemberuumeme19:05 16 Aug '05  
GeneralRe: why does it has error when running? PinmemberMaxim Alekseikin4:35 18 Aug '05  
GeneralThank! PinmemberJaimirG5:48 20 Jun '05  
GeneralLoad Pinmemberrm_babar20:40 28 Apr '05  
GeneralError Pinmemberlyptus11:53 23 Feb '05  
GeneralRe: Error Pinmemberlyptus11:57 23 Feb '05  
GeneralRe: Error PinmemberMaxim Alekseikin, MCAD4:00 24 Feb '05  

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Web04 | 2.5.120529.1 | Last Updated 24 Aug 2005
Article Copyright 2005 by Maxim Alekseykin
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid