Image 與 byte[] 互轉

01 /// <summary>
02         /// 將 Byte 陣列轉換為 Image。
03         /// </summary>
04         /// <param name="Buffer">Byte 陣列。</param>        
05         public static Image BufferToImage(byte[] Buffer) {
06             if (Buffer == null || Buffer.Length == 0) { return null; }
07             byte[] data = null;
08             Image oImage = null;
09             Bitmap oBitmap = null;
10             //建立副本
11             data = (byte[])Buffer.Clone();
12             try {
13                 MemoryStream oMemoryStream = new MemoryStream(Buffer);
14                 //設定資料流位置
15                 oMemoryStream.Position = 0;
16                 oImage = System.Drawing.Image.FromStream(oMemoryStream);
17                 //建立副本
18                 oBitmap = new Bitmap(oImage); 
19             }
20             catch {
21                 throw;
22             }
23             //return oImage;
24             return oBitmap;
25         }

 

sample2 將 Image 轉換為 Byte 陣列。

01 /// <summary>
02         /// 將 Image 轉換為 Byte 陣列。
03         /// </summary>
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; }
08             byte[] data = null;
09             using (MemoryStream oMemoryStream = new MemoryStream()) {
10                 //建立副本
11                 using (Bitmap oBitmap = new Bitmap(Image)) {
12                     //儲存圖片到 MemoryStream 物件,並且指定儲存影像之格式
13                     oBitmap.Save(oMemoryStream, imageFormat);
14                     //設定資料流位置
15                     oMemoryStream.Position = 0;
16                     //設定 buffer 長度
17                     data = new byte[oMemoryStream.Length];
18                     //將資料寫入 buffer
19                     oMemoryStream.Read(data, 0, Convert.ToInt32(oMemoryStream.Length));
20                     //將所有緩衝區的資料寫入資料流
21                     oMemoryStream.Flush();
22                 }
23             }
24             return data;
25         }

 

posted @ 2010-08-28 13:45  Wind&#183;e  阅读(257)  评论(0编辑  收藏  举报