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 }
如果现在不努力,以后会活的更累吧。