posted by By훈트 2010.07.30 14:36

MemoryStream

Saving-Rebuilding InkCanvas Strokes

Load/Unload images into/from DB table

C# Image to Byte Array and Byte Array to Image Converter Class

 

Introduction

Recently I was looking for a class which could convert a System.Drawing.Image to byte[] array and vice versa. After a lot of searching on Google, I realised that it would be faster for me to write this class and also share it with the community.

The class which I wrote is called ImageConverter.cs. The class has two methods.

First method: Convert Image to byte[] array:

 Collapse Copy Code
public byte[] imageToByteArray(System.Drawing.Image imageIn)
{
 MemoryStream ms = new MemoryStream();
 imageIn.Save(ms,System.Drawing.Imaging.ImageFormat.Gif);
 return  ms.ToArray();
}

This method uses the System.Drawing.Image.Save method to save the image to a memorystream. The memorystream can then be used to return a byte array using the ToArray() method in the MemoryStream class.

Second method: Convert byte[] array to Image:

 Collapse Copy Code
public Image byteArrayToImage(byte[] byteArrayIn)
{
     MemoryStream ms = new MemoryStream(byteArrayIn);
     Image returnImage = Image.FromStream(ms);
     return returnImage;
}

This method uses the Image.FromStream method in the Image class to create a method from a memorystream which has been created using a byte array. The image thus created is returned in this method.

The way I happen to use this method was to transport an image to a web service, by converting it to a byte array and vice-versa.

Hope this class is useful to the community as well. The code of ImageConverter.cs can be downloaded from the link at the top of this article.

Rajan Tawate

Founder
Seegloo Web Meeting

 

 

 

 

 

 

 

--------------

 

Store Image into DB table

 Collapse Copy Code
...
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.

 Collapse Copy Code
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

 Collapse Copy Code
 // 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.

<FORM style="PADDING-BOTTOM: 0px; MARGIN: 0px; PADDING-LEFT: 0px; PADDING-RIGHT: 0px; PADDING-TOP: 0px" id=aspnetForm method=post name=aspnetForm action=DisplayArticle.aspx>

<INPUT id="__VIEWSTATE" value="/wEPDwUKMTAyMTMzODg1Ng9kFgJmD2QWBAIJD2QWBAIFDw8WAh4HVmlzaWJsZWdkZAINDw8WAh8AZ2RkAgoPZBYKAgcPZBYOAgEPZBYCZg8WAh4LXyFJdGVtQ291bnRmZAIDD2QWCGYPDxYCHgtOYXZpZ2F0ZVVybAUpL0tCL2RhdGFiYXNlL2ltYWdlczJkYi5hc3B4P2Rpc3BsYXk9UHJpbnRkZAICDw8WAh8AaGRkAgMPZBYGAgIPDxYCHghJbWFnZVVybAUhL3NjcmlwdC9Cb29rbWFya3MvSW1hZ2VzL2xpbmsucG5nZGQCBA8PFgIfAgU/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EQ8WAh8HBQsyNCBBdWcgMjAwNWQCEw8PFgQfBwUOU21pdGhhIFZpamF5YW4fAgUmL3NjcmlwdC9NZW1iZXJzaGlwL1ZpZXcuYXNweD9taWQ9Mjg5NzBkZAIVDxYCHwcFIkNvcHlyaWdodCAyMDA1IGJ5IE1heGltIEFsZWtzZXlraW5kZHoy3t5b1AFEWlnw6kJkhmg0NxIO" type="hidden" name="__VIEWSTATE">
<INPUT id="__EVENTVALIDATION" value="/wEWCALryJLaBgLAlMXDBwLBlMXDBwLClMXDBwLDlMXDBwLElMXDBwLP+++tCwK5upDkC+Baommd5pH6A8nKaeXZ0JWo3SoP" type="hidden" name="__EVENTVALIDATION">

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

 

</FORM> 

 

 

 

 

--------------------------

 

 

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();
   }
}

신고
크리에이티브 커먼즈 라이선스
Creative Commons License

티스토리 툴바