【转】Byte[]、Image、Bitmap 之间的相互转换

 1 /// <summary>
 2 /// 将图片Image转换成Byte[]
 3 /// </summary>
 4 /// <param name="Image">image对象</param>
 5 /// <param name="imageFormat">后缀名</param>
 6 /// <returns></returns>
 7 public static byte[] ImageToBytes(Image Image, System.Drawing.Imaging.ImageFormat imageFormat)
 8 {
 9     if (Image == null) { return null; }
10     byte[] data = null;
11     using (MemoryStream ms = new MemoryStream())
12     {
13         using (Bitmap Bitmap = new Bitmap(Image))
14         {
15             Bitmap.Save(ms, imageFormat);
16             ms.Position = 0;
17             data = new byte[ms.Length];
18             ms.Read(data, 0, Convert.ToInt32(ms.Length));
19             ms.Flush();
20         }
21     }
22     return data;
23 }

 

 1 /// <summary>
 2 /// byte[]转换成Image
 3 /// </summary>
 4 /// <param name="byteArrayIn">二进制图片流</param>
 5 /// <returns>Image</returns>
 6 public static System.Drawing.Image byteArrayToImage(byte[] byteArrayIn)
 7 {
 8     if (byteArrayIn == null)
 9         return null;
10     using (System.IO.MemoryStream ms = new System.IO.MemoryStream(byteArrayIn))
11     {
12         System.Drawing.Image returnImage = System.Drawing.Image.FromStream(ms);
13         ms.Flush();
14         return returnImage;
15     }
16 }

 

//Image转换Bitmap

1. Bitmap img = new Bitmap(imgSelect.Image);

2. Bitmap bmp = (Bitmap)pictureBox1.Image;

 

 1 //Bitmap转换成Image
 2 private static System.Windows.Controls.Image Bitmap2Image(System.Drawing.Bitmap Bi)
 3 {
 4     MemoryStream ms = new MemoryStream();
 5     Bi.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
 6     BitmapImage bImage = new BitmapImage();
 7     bImage.BeginInit();
 8     bImage.StreamSource = new MemoryStream(ms.ToArray());
 9     bImage.EndInit();
10     ms.Dispose();
11     Bi.Dispose();
12     System.Windows.Controls.Image i = new System.Windows.Controls.Image();
13     i.Source = bImage;
14     return i;
15 }
16 
17 
18 
19 //byte[] 转换 Bitmap
20 public static Bitmap BytesToBitmap(byte[] Bytes)
21 {
22     MemoryStream stream = null;
23     try
24     {
25         stream = new MemoryStream(Bytes);
26         return new Bitmap((Image)new Bitmap(stream));
27     }
28     catch (ArgumentNullException ex)
29     {
30         throw ex;
31     }
32     catch (ArgumentException ex)
33     {
34         throw ex;
35     }
36     finally
37     {
38         stream.Close();
39     }
40 }
41 
42 //Bitmap转byte[]  
43 public static byte[] BitmapToBytes(Bitmap Bitmap)
44 {
45     MemoryStream ms = null;
46     try
47     {
48         ms = new MemoryStream();
49         Bitmap.Save(ms, Bitmap.RawFormat);
50         byte[] byteImage = new Byte[ms.Length];
51         byteImage = ms.ToArray();
52         return byteImage;
53     }
54     catch (ArgumentNullException ex)
55     {
56         throw ex;
57     }
58     finally
59     {
60         ms.Close();
61     }
62 }

 

posted @ 2018-03-31 16:03  死鱼眼の猫  阅读(154)  评论(0编辑  收藏  举报