码迷,mamicode.com
首页 > Windows程序 > 详细

C# base64 Img 互转

时间:2015-09-11 19:22:01      阅读:341      评论:0      收藏:0      [点我收藏+]

标签:

[AcceptVerbs(HttpVerbs.Post)]
public JsonResult Upload(HttpPostedFileBase fileData)
{
try
{
if (fileData != null)
{
string ext = Path.GetExtension(fileData.FileName).Remove(0, 1); // 文件扩展名
Image img = Image.FromStream(fileData.InputStream);
Bitmap bmp = new Bitmap(img);
MemoryStream stream = new MemoryStream();
bmp.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp);
stream.Position = 0;
byte[] data = new byte[stream.Length];
stream.Read(data, 0, (int)stream.Length);
stream.Close();
string base64String = "data:" + ext + ";base64," + Convert.ToBase64String(data, 0, data.Length);
return Json(base64String, JsonRequestBehavior.AllowGet);
}
}
catch (Exception)
{
}
return Json(null, JsonRequestBehavior.AllowGet);
}
public string Base64ToImg(string base64)
{
try
{
int len = base64.IndexOf("base64,") + 7;
int len1 = base64.IndexOf("data:") + 5;
string ext = base64.Substring(len1, len - len1 - 8);
string filePath = "/Content/newsImg/" + DateTime.Now.ToString("yyyyMMddHHmmssfff.") + ext;
base64 = base64.Remove(0, len);
byte[] arr = Convert.FromBase64String(base64);
MemoryStream ms = new MemoryStream(arr);
Bitmap bmp = new Bitmap(ms);
bmp.Save(Server.MapPath(filePath), ext.ToLower().Contains("png") ? System.Drawing.Imaging.ImageFormat.Png : System.Drawing.Imaging.ImageFormat.Jpeg);
ms.Close();
return filePath;
}
catch (Exception)
{
}
return "";
}

C# base64 Img 互转

标签:

原文地址:http://www.cnblogs.com/liuph/p/4801703.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!