• C# base64 Img 互转


     1 [AcceptVerbs(HttpVerbs.Post)]
     2 public JsonResult Upload(HttpPostedFileBase fileData)
     3 {
     4 try
     5 {
     6 if (fileData != null)
     7 {
     8 string ext = Path.GetExtension(fileData.FileName).Remove(0, 1); // 文件扩展名
     9 Image img = Image.FromStream(fileData.InputStream);
    10 Bitmap bmp = new Bitmap(img);
    11 MemoryStream stream = new MemoryStream();
    12 bmp.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp);
    13 stream.Position = 0;
    14 byte[] data = new byte[stream.Length];
    15 stream.Read(data, 0, (int)stream.Length);
    16 stream.Close();
    17 string base64String = "data:" + ext + ";base64," + Convert.ToBase64String(data, 0, data.Length);
    18 return Json(base64String, JsonRequestBehavior.AllowGet);
    19 }
    20 }
    21 catch (Exception)
    22 {
    23 }
    24 return Json(null, JsonRequestBehavior.AllowGet);
    25 }
    26 public string Base64ToImg(string base64)
    27 {
    28 try
    29 {
    30 int len = base64.IndexOf("base64,") + 7;
    31 int len1 = base64.IndexOf("data:") + 5;
    32 string ext = base64.Substring(len1, len - len1 - 8);
    33 string filePath = "/Content/newsImg/" + DateTime.Now.ToString("yyyyMMddHHmmssfff.") + ext;
    34 base64 = base64.Remove(0, len);
    35 byte[] arr = Convert.FromBase64String(base64);
    36 MemoryStream ms = new MemoryStream(arr);
    37 Bitmap bmp = new Bitmap(ms);
    38 bmp.Save(Server.MapPath(filePath), ext.ToLower().Contains("png") ? System.Drawing.Imaging.ImageFormat.Png : System.Drawing.Imaging.ImageFormat.Jpeg);
    39 ms.Close();
    40 return filePath;
    41 }
    42 catch (Exception)
    43 {
    44 }
    45 return "";
    46 }
    View Code
  • 相关阅读:
    Centos 7升级gcc版本和CXXABI_1.3.8' not found错误解决
    Websphere缓存问题
    K8S中文官档地址
    可视化vscode安装matplotlib工具
    如何下载zoom上别人录制的视频?
    马士兵23设计模式
    DDD 领域驱动
    UPX手动脱壳/程序脱壳
    切换jdk环境d的n种办法
    近期ctf*web*一览
  • 原文地址:https://www.cnblogs.com/liuph/p/4801703.html
Copyright © 2020-2023  润新知