图片转换器
1 public class FormatChange 2 { 3 /// <summary> 4 /// 转片转字符串 5 /// </summary> 6 /// <param name="image"></param> 7 /// <returns></returns> 8 public static string ChangeImageToString(Image image) 9 { 10 string result = null; 11 try 12 { 13 MemoryStream ms = new MemoryStream(); 14 image.Save(ms, image.RawFormat); 15 byte[] arr = new byte[ms.Length]; 16 ms.Position = 0; 17 ms.Read(arr, 0, (int)ms.Length); 18 ms.Close(); 19 result = Convert.ToBase64String(arr); 20 } 21 catch (Exception) 22 { 23 result = null; 24 } 25 return result; 26 } 27 /// <summary> 28 /// 字符转转图片 29 /// </summary> 30 /// <param name="pic"></param> 31 /// <returns></returns> 32 public static Image ChangeStringToImage(string pic) 33 { 34 try 35 { 36 byte[] imageBytes = Convert.FromBase64String(pic); 37 //读入MemoryStream对象 38 MemoryStream memoryStream = new MemoryStream(imageBytes, 0, imageBytes.Length); 39 memoryStream.Write(imageBytes, 0, imageBytes.Length); 40 //转成图片 41 Image image = Image.FromStream(memoryStream); 42 43 return image; 44 } 45 catch (Exception) 46 { 47 return null; 48 } 49 } 50 51 /// <summary> 52 /// 将图片转换为BYTE流 53 /// </summary> 54 /// <param name="img"></param> 55 /// <returns></returns> 56 public static Byte[] ImgToByte(Image img) 57 { 58 Byte[] result = null; 59 try 60 { 61 MemoryStream ms = new MemoryStream(); 62 img.Save(ms,img.RawFormat); 63 byte[] arr = new byte[ms.Length]; 64 ms.Position = 0; 65 ms.Read(arr, 0, (int)ms.Length); 66 result = arr; 67 ms.Close(); 68 } 69 catch (Exception ex) 70 { 71 throw ex; 72 } 73 74 return result; 75 76 } 77 /// <summary> 78 /// 将BYTE流转图片 79 /// </summary> 80 /// <param name="btye"></param> 81 /// <returns></returns> 82 public static Image ByteToImg(Byte[] btye) 83 { 84 Image result = null; 85 try 86 { 87 MemoryStream memoryStream = new MemoryStream(btye, 0, btye.Length); 88 memoryStream.Write(btye, 0, btye.Length); 89 //转成图片 90 result = Image.FromStream(memoryStream); 91 } 92 catch (Exception) 93 { 94 95 throw; 96 } 97 return result; 98 } 99 }