C# 圖片與Base64的相互轉化

public ActionResult UploadSignature2(string src_data) { Class1.Base64StrToImage(src_data, "C:\\Users\\45448\\Desktop\\1\\"+ DateTime.Now.ToString("yyyyMMddHHss") + ".png"); return Json(1, JsonRequestBehavior.AllowGet); } /// <summary>
        /// 將Base64字符串轉換爲圖片並保存到本地 /// </summary>
        /// <param name="base64Str">base64字符串</param>
        /// <param name="savePath">圖片保存地址,如:/Content/Images/10000.png</param>
        /// <returns></returns>
        public static bool Base64StrToImage(string base64Str, string savePath) { var ret = true; try { base64Str = base64Str.Replace("data:image/png;base64,", "").Replace("data:image/jgp;base64,", "") .Replace("data:image/jpg;base64,", "").Replace("data:image/jpeg;base64,", ""); //將base64頭部信息替換
                var bitmap = Base64StrToImage(base64Str); if (bitmap != null) { //建立文件夾
                    var folderPath = savePath.Substring(0, savePath.LastIndexOf('\\')); ////FileHelper.CreateDir(folderPath);
                    if (!Directory.Exists(folderPath)) { Directory.CreateDirectory(folderPath); } //圖片後綴格式
                    var suffix = savePath.Substring(savePath.LastIndexOf('.') + 1, savePath.Length - savePath.LastIndexOf('.') - 1).ToLower(); var suffixName = suffix == "png"
                        ? ImageFormat.Png : suffix == "jpg" || suffix == "jpeg"
                            ? ImageFormat.Jpeg : suffix == "bmp"
                                ? ImageFormat.Bmp : suffix == "gif"
                                    ? ImageFormat.Gif : ImageFormat.Jpeg; //這裏複製一份對圖像進行保存,不然會出現「GDI+ 中發生通常性錯誤」的錯誤提示
                    var bmpNew = new Bitmap(bitmap); bmpNew.Save(savePath, suffixName); bmpNew.Dispose(); bitmap.Dispose(); } else { ret = false; } } catch (Exception ex) { ret = false; } return ret; } 複製代碼 複製代碼 /// <summary>
        /// Image 轉成 base64 /// </summary>
        /// <param name="fileFullName"></param>
        public static string ImageToBase64(string fileFullName) { try { Bitmap bmp = new Bitmap(fileFullName); MemoryStream ms = new MemoryStream(); var suffix = fileFullName.Substring(fileFullName.LastIndexOf('.') + 1, fileFullName.Length - fileFullName.LastIndexOf('.') - 1).ToLower(); var suffixName = suffix == "png"
                    ? ImageFormat.Png : suffix == "jpg" || suffix == "jpeg"
                        ? ImageFormat.Jpeg : suffix == "bmp"
                            ? ImageFormat.Bmp : suffix == "gif"
                                ? ImageFormat.Gif : ImageFormat.Jpeg; bmp.Save(ms, suffixName); byte[] arr = new byte[ms.Length]; ms.Position = 0; ms.Read(arr, 0, (int)ms.Length); ms.Close(); return Convert.ToBase64String(arr); } catch (Exception ex) { return null; } }
相關文章
相關標籤/搜索