C# byte数组与Image的相互转换
功能需求:
1、把一张图片(png bmp jpeg bmp gif)转换为byte数组存放到数据库。
2、把从数据库读取的byte数组转换为Image对象,赋值给相应的控件显示。
3、从图片byte数组得到对应图片的格式,生成一张图片保存到磁盘上。
这里的Image是System.Drawing.Image。
1 //Get an image from file 2 Image image = Image.FromFile("D:\test.jpg"); 3 Bitmap bitmap = new Bitmap("D:\test.jpg");
以下三个函数分别实现了上述三个需求:
1 using System; 2 using System.Collections.Generic; 3 using System.Drawing; 4 using System.Drawing.Imaging; 5 using System.IO; 6 using System.Linq; 7 using System.Text; 8 9 namespace NetUtilityLib 10 { 11 public static class ImageHelper 12 { 13 /// <summary> 14 /// Convert Image to Byte[] 15 /// </summary> 16 /// <param name="image"></param> 17 /// <returns></returns> 18 public static byte[] ImageToBytes(Image image) 19 { 20 ImageFormat format = image.RawFormat; 21 using (MemoryStream ms = new MemoryStream()) 22 { 23 if (format.Equals(ImageFormat.Jpeg)) 24 { 25 image.Save(ms, ImageFormat.Jpeg); 26 } 27 else if (format.Equals(ImageFormat.Png)) 28 { 29 image.Save(ms, ImageFormat.Png); 30 } 31 else if (format.Equals(ImageFormat.Bmp)) 32 { 33 image.Save(ms, ImageFormat.Bmp); 34 } 35 else if (format.Equals(ImageFormat.Gif)) 36 { 37 image.Save(ms, ImageFormat.Gif); 38 } 39 else if (format.Equals(ImageFormat.Icon)) 40 { 41 image.Save(ms, ImageFormat.Icon); 42 } 43 byte[] buffer = new byte[ms.Length]; 44 //Image.Save()会改变MemoryStream的Position,需要重新Seek到Begin 45 ms.Seek(0, SeekOrigin.Begin); 46 ms.Read(buffer, 0, buffer.Length); 47 return buffer; 48 } 49 } 50 51 /// <summary> 52 /// Convert Byte[] to Image 53 /// </summary> 54 /// <param name="buffer"></param> 55 /// <returns></returns> 56 public static Image BytesToImage(byte[] buffer) 57 { 58 MemoryStream ms = new MemoryStream(buffer); 59 Image image = System.Drawing.Image.FromStream(ms); 60 return image; 61 } 62 63 /// <summary> 64 /// Convert Byte[] to a picture and Store it in file 65 /// </summary> 66 /// <param name="fileName"></param> 67 /// <param name="buffer"></param> 68 /// <returns></returns> 69 public static string CreateImageFromBytes(string fileName, byte[] buffer) 70 { 71 string file = fileName; 72 Image image = BytesToImage(buffer); 73 ImageFormat format = image.RawFormat; 74 if (format.Equals(ImageFormat.Jpeg)) 75 { 76 file += ".jpeg"; 77 } 78 else if (format.Equals(ImageFormat.Png)) 79 { 80 file += ".png"; 81 } 82 else if (format.Equals(ImageFormat.Bmp)) 83 { 84 file += ".bmp"; 85 } 86 else if (format.Equals(ImageFormat.Gif)) 87 { 88 file += ".gif"; 89 } 90 else if (format.Equals(ImageFormat.Icon)) 91 { 92 file += ".icon"; 93 } 94 System.IO.FileInfo info = new System.IO.FileInfo(file); 95 System.IO.Directory.CreateDirectory(info.Directory.FullName); 96 File.WriteAllBytes(file, buffer); 97 return file; 98 } 99 } 100 }