原文處
Introduction
有的時候我們必須將 Image 物件轉為 byte[] 陣列,也可能將 byte[] 轉換為 Image 物件,
例如 : 圖檔通常都是以二進位的方式存在於資料庫,當資料撈出來時,也許會需要先轉換成 Image 的格式,再做圖片匯製或是其他處理。
Example
修改 20100113
sample1 將 Byte 陣列轉換為 Image。
view source
print?
02 | /// 將 Byte 陣列轉換為 Image。 |
04 | /// <param name="Buffer">Byte 陣列。</param> |
05 | public static Image BufferToImage(byte[] Buffer) { |
06 | if (Buffer == null || Buffer.Length == 0) { return null; } |
09 | Bitmap oBitmap = null; |
11 | data = (byte[])Buffer.Clone(); |
13 | MemoryStream oMemoryStream = new MemoryStream(Buffer); |
15 | oMemoryStream.Position = 0; |
16 | oImage = System.Drawing.Image.FromStream(oMemoryStream); |
18 | oBitmap = new Bitmap(oImage); |
sample2 將 Image 轉換為 Byte 陣列。
view source
print?
02 | /// 將 Image 轉換為 Byte 陣列。 |
04 | /// <param name="Image">Image 。</param> |
05 | /// <param name="imageFormat">指定影像格式。</param> |
06 | public static byte[] ImageToBuffer(Image Image, System.Drawing.Imaging.ImageFormat imageFormat) { |
07 | if (Image == null) { return null; } |
09 | using (MemoryStream oMemoryStream = new MemoryStream()) { |
11 | using (Bitmap oBitmap = new Bitmap(Image)) { |
12 | //儲存圖片到 MemoryStream 物件,並且指定儲存影像之格式 |
13 | oBitmap.Save(oMemoryStream, imageFormat); |
15 | oMemoryStream.Position = 0; |
17 | data = new byte[oMemoryStream.Length]; |
19 | oMemoryStream.Read(data, 0, Convert.ToInt32(oMemoryStream.Length)); |
21 | oMemoryStream.Flush(); |
|