base64编码的字符串与图片相互转换

 1         #region 图片转为base64编码的字符串---ImgToBase64String
 2         /// <summary>
 3         /// 图片转为base64编码的字符串
 4         /// </summary>
 5         /// <param name="Imagefilename">图片地址</param>
 6         /// <returns></returns>
 7         public static List<publicAnnex> ImgToBase64String(string Imagefilename)
 8         {
 9             try
10             {
11                 var AList = new List<publicAnnex>();
12                 var Listarr = Imagefilename.Split(',');
13                 foreach (var item in Listarr)
14                 {
15                     string uppath = System.Web.HttpContext.Current.Server.MapPath(item);
16                     Bitmap bmp = new Bitmap(uppath);
17                     MemoryStream ms = new MemoryStream();
18                     bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
19                     byte[] arr = new byte[ms.Length];
20                     ms.Position = 0;
21                     ms.Read(arr, 0, (int)ms.Length);
22                     ms.Close();
23                     var A = new publicAnnex();
24                     A.Content = Convert.ToBase64String(arr);
25                     AList.Add(A);
26                 }
27                 return AList;
28             }
29             catch (Exception ex)
30             {
31                 return null;
32             }
33         }
34         #endregion
35 
36         #region base64编码的字符串转为图片---Base64StringToImage
37         /// <summary>
38         /// base64编码的字符串转为图片
39         /// </summary>
40         /// <param name="strbase64">字符串</param>
41         /// <returns></returns>
42         public static string Base64StringToImage(List<string> strbase64)
43         {
44             try
45             {
46                 var AnnexAddress = "";
47                 foreach (var item in strbase64)
48                 {
49                     string time = DateTime.Now.ToString("yyyyMMddHHmmssffff");
50                     byte[] arr = Convert.FromBase64String(item);
51                     MemoryStream ms = new MemoryStream(arr);
52                     Bitmap bmp = new Bitmap(ms);
53                     string uppath = System.Web.HttpContext.Current.Server.MapPath("~/UploadFiles/Image/") + "YMD_" + time + ".jpg";
54                     bmp.Save(uppath);
55                     ms.Close();
56                     AnnexAddress += "/UploadFiles/Image/YMD_" + time + ".jpg,";
57                 }
58                 AnnexAddress.Substring(0, AnnexAddress.Length - 1);
59                 return AnnexAddress;
60             }
61             catch (Exception ex)
62             {
63                 return null;
64             }
65         }
66         #endregion

 

posted @ 2018-06-15 14:09  风中起舞  阅读(853)  评论(0编辑  收藏  举报