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:
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
:
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
FounderSeegloo Web Meeting
--------------
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.
<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>
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();
}
}
'Programming > C#' 카테고리의 다른 글
[C#] Windows 해상도 가져오기 (0) | 2010.11.16 |
---|---|
[C#] 마우스 좌표얻기 (1) | 2010.11.03 |
[C#] Image Scale 함수, 이미지의 크기를 퍼센트, 특정Size 별로 조정하기 (0) | 2010.11.01 |
[C#] form 이벤트 발생순서 (0) | 2010.10.22 |
[C#] C#에서 ConnectionString 작성법! (0) | 2010.09.17 |