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
posted by By훈트 2010.07.29 21:26

이미지에 관련된 전반적인 사항이니 참고하세요.

 

1. 기본적으로 resource에 저장되어 있는 이미지의 경우 Drawable이라는 오브젝트를 구해와서 화면에 그릴 수가 있습니다.

 

Drawable drawable = getResources().getDrawable(id);

drawable.setBounds(0,0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());  // drawable을 어느 영역에 그릴 것인가?

 

onDraw(canvas canvas) {

           drawable.draw(canvas);

}

 

setBounds에 설정한 값에 따라서 자동으로 이미지가 scaling이 됩니다.

 

원본 이미지 사이즈가 100*50인데 bounds를  (0,0, 200, 100)이라고 설정하면 가로 세로가 2배로 확대되어서 그려지겠죠.

 

2. 임의의 bitmap을 생성하고 bitmap에 원하는 내용그리기

 

다음과 같이 임의의 bitmap을 생성합니다.

Bitmap bitmap = Bitmap.createBitmap(width, height, Config.ARGB_8888);

 

Config.ARGB_8888말고 Config.RGB_565 있고 몇가지 있습니다.

 

원하는 걸로 생성하면 되는데 ARGB8888 생성할 경우 투명값을 지정할 수가 있는 반면 RGB_565 생성하시면 불투명한 이미지만 가능합니다.

 

이렇게 만들어진 bitmap에 직접 그림을 그리거나 다른 이미지를 그릴려고 하면 아래와 같이 새로운 canvas를 만들어야 합니다.

 

Canvas canvas = new Canvas();

canvas.setBitmap(bitmap);

 

그러면 향후에 canvas에 그리는 모든 작업은 bitmap에 반영이 됩니다.

 

3. Bitmap Drawable간의 변환

 

안드로이드에서는 bitmap을 직접 다루기보단 대부분 Drawable이라는 wrapping된 형태로 이미지를 처리하기 때문에

 

Bitmap의 경우 종종 Drawable로 변환해야 하는 경우가 있습니다.

 

이를 위해서 BitmapDrawable이라는 클래스가 존재하고 아래와 같은 식으로 사용이 가능합니다.

 

Drawable drawable = (Drawable)(new BitmapDrawable(bitmap));

 

BitmapDrawable은 Drawable로 캐스팅이 가능하죠.

 

4. canvas 처리

 

w*h크기의 drawable 오브젝트가 있을 때 setBounds를 이용하여 임의의 좌표(x,y)에 원형크기대로 출력할려면 아래와 같습니다.

 

obj.setBounds(x,y,x+w,y+h);

obj.draw(canvas);

 

이 방식의 귀찮은 점은 항상 w,h를 지정을 해줘야 하기 때문에 코드도 상당히 길어지고 지저분해보이는 경우가 많습니다.

(getIntrinsicWidth()/Height()로 항상 구하던지 별도의 변수에 값을 유지해야하죠)

 

그래서 위와 같은 방법보다는 아래와 같이 canvas의 좌표이동 변환식을 이용하는게 깔끔합니다.

 

obj.setBounds(0,0,w,h); // 얘는 drawable을 최초로 생성했을 때 한번만 지정하면 됨

 

canvas.save(); // 현재 변환식을 저장

canvas.translate(x,y) // 좌표이동과 관련된 변환식 적용

obj.draw(canvas); // drawable을 그린다.

canvas.restore(); // 원래 변환식으로 복구

 

canvas.translate(x,y) 를 지정할 경우 출력할 이미지를 (x,y)만큼 이동시켜서 그려줍니다. (좌표이동 행렬식이라고 생각하면 됨)

 

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

티스토리 툴바