C#图片转字符串------>>>>字符串在转回图片两种方法
1 #region 调用方法 2 private void Form1_Load(object sender, EventArgs e) 3 { 4 OpenFileDialog dialog = new OpenFileDialog(); 5 dialog.Multiselect = true;//该值确定是否可以选择多个文件 6 dialog.Title = "请选择文件夹"; 7 dialog.Filter = "所有文件(*.*)|*.*"; 8 if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK) 9 { 10 string file = dialog.FileName; 11 var imageString = ImageConvertString(file); 12 var iamgePath = StringToImage(imageString); 13 14 var downImageString = DownloadImageConvertString(file); 15 var downIamgePath = StringConvertImage(imageString); 16 } 17 } 18 #endregion 19 #region 网络图片转换 20 public string DownloadImageConvertString(string imagepath) 21 { 22 using (System.Net.WebClient wc = new System.Net.WebClient()) 23 { 24 wc.Headers.Add("User-Agent", "Chrome"); 25 return Convert.ToBase64String(wc.DownloadData(imagepath)); 26 } 27 } 28 public static string StringConvertImage(string buffer, string fileName = "bg_print1") 29 { 30 string path = string.Format("{0}/{1}{2}.png", System.Environment.CurrentDirectory, System.DateTime.Now.ToString("yyyyMMddHHmmss"), fileName); 31 byte[] bytes = Convert.FromBase64String(buffer); 32 MemoryStream ms = new MemoryStream(); 33 ms.Write(bytes, 0, bytes.Length); 34 Bitmap bmp = new Bitmap(ms); 35 if (Directory.Exists(path)) 36 { 37 Directory.Delete(path); 38 } 39 bmp.Save(path); 40 return path; 41 } 42 #endregion 43 #region 本地图片转换 44 /// <summary> 45 /// Base64String转本地图片 46 /// </summary> 47 /// <param name="buffer">Base64String</param> 48 /// <param name="fileName">文件名</param> 49 /// <returns></returns> 50 public static string StringToImage(string buffer, string fileName = "bg_print2") 51 { 52 string path = string.Format("{0}/{1}{2}.png", System.Environment.CurrentDirectory, System.DateTime.Now.ToString("yyyyMMddHHmmss"), fileName); 53 using (MemoryStream ms = new MemoryStream(Convert.FromBase64String(buffer))) 54 { 55 using (Image image = System.Drawing.Image.FromStream(ms)) 56 { 57 if (Directory.Exists(path)) 58 { 59 Directory.Delete(path); 60 } 61 image.Save(path); 62 return path; 63 } 64 } 65 } 66 /// <summary> 67 /// 本地图片文件转Base64字符串 68 /// </summary> 69 /// <param name="imagepath">本地文件路径</param> 70 /// <returns>Base64String</returns> 71 public string ImageConvertString(string imagepath) 72 { 73 using (FileStream fs = new FileStream(imagepath, FileMode.Open)) 74 { 75 byte[] byData = new byte[fs.Length]; 76 fs.Read(byData, 0, byData.Length); 77 fs.Close(); 78 return Convert.ToBase64String(byData); 79 } 80 } 81 #endregion