标签:
[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 "";
}
标签:
原文地址:http://www.cnblogs.com/liuph/p/4801703.html