直接上代码:
/// <summary> /// 将Base64字符串转换为图片并保存到本地 /// </summary> /// <param name="base64Str">访问的txt文件路径</param> /// <param name="savePath">图片保存地址,如:/Content/Images/10000.png</param> /// <returns></returns> public static bool Base64StrToImage(string txtPath, string savePath) { var ret = true; try { var ds= System.IO.File.ReadAllText(txtPath); ds = ds.Replace(" ",""); ds = ds.Replace(" ",""); var data = JsonConvert.DeserializeObject<Rootobject>(ds); List<string> base64s = new List<string>();//所有的图片base64 data.Result.Data.XXCJ_TX.ROW.ForEach(e=>base64s.Add(e.TX)); data.Result.Data.XXCJ_TSBJ.ROW.ForEach(e=>base64s.Add(e.BJ)); data.Result.Data.XXCJ_BT.ROW.ForEach(e=>base64s.Add(e.DATA)); data.Result.Data.XXCJ_ZWPHOTO.ROW.ForEach(e=>base64s.Add(e.ZWXP)); foreach (var item in base64s) {byte[] arr2 = Convert.FromBase64String(item); using (MemoryStream ms2 = new MemoryStream(arr2)) { try { Image mImage = Image.FromStream(ms2); System.Drawing.Bitmap bmp2 = new System.Drawing.Bitmap(mImage); if (!Directory.Exists(Directory.GetCurrentDirectory() + savePath)) { Directory.CreateDirectory(Directory.GetCurrentDirectory() + savePath); } bmp2.Save(Directory.GetCurrentDirectory() + savePath + "/" + DateTime.Now.ToString("yyyyMMddHHss") + ".jpg", System.Drawing.Imaging.ImageFormat.Jpeg); bmp2.Dispose(); } catch { //Console.WriteLine(item);//记录错误的图片 continue; } } } } catch (Exception ex) { ret = false; } return ret; }
调用示例:
var temp = Base64StrToImage(@"C:UsersAdministratorDocumentsWeChat Fileswang2580288017FileStorageFile2019-12zhiwen.txt", "/base64Images");
对于里面的类 太多(太麻烦)就不贴了,大致思路和逻辑是没问题的!!