.NET MVC 后台接受base64的上传图片

时间:2022-09-06 21:57:01
         #region 配合前端的多张图片上传
#region 上传图片方法
/// <summary>
/// 接口方法
/// </summary>
/// <param name="img">带 data:image/jpeg;base64,的base64的图片</param>
/// <returns>图片路径</returns>
[HttpPost]
public ActionResult GETaddimg2(String img)
{
if (img == null)
{
return Json("空");
}
else
{
return Json(PDUploadImage(img), JsonRequestBehavior.AllowGet);
}
}
#endregion
#region 图片转化
/// <summary>
/// base64 的字符串
/// </summary>
/// <param name="img"></param>
/// <returns>图片转成32的名字</returns>
public JsonResult PDUploadImage(string img)
{
string error = "";
return Json(SaveImage("/Upload/Article", img, ref error), JsonRequestBehavior.AllowGet);
}
#endregion
#region 截取data:image/jpeg;base64,提取图片,并保存图片
/// <summary>
/// 截取data:image/jpeg;base64,提取图片,并保存图片
/// </summary>
/// <param name="file_name"></param>
/// <param name="img_string">base64的字符串</param>
/// <param name="error">错误的图片格式</param>
/// <returns>路径 + 图片的名称</returns>
private string SaveImage(string file_name, string img_string, ref string error)
{
//try
//{
string[] img_array = img_string.Split(',');
byte[] arr = Convert.FromBase64String(img_array[]);
using (MemoryStream ms = new MemoryStream(arr))
{
Bitmap bmp = new Bitmap(ms);
if (img_array[].ToLower() == "data:image/jpeg;base64")
{
bmp.Save(file_name + ".jpg");
return SetImg(Guid.NewGuid().ToString().Replace('-', 'p').Substring(), "jpg", arr);
}
else if (img_array[].ToLower() == "data:image/png;base64")
{
bmp.Save(file_name + ".png");
return SetImg(Guid.NewGuid().ToString().Replace('-', 'p').Substring(), "png", arr);
}
else if (img_array[].ToLower() == "data:image/gif;base64")
{
bmp.Save(file_name + ".gif");
return SetImg(Guid.NewGuid().ToString().Replace('-', 'p').Substring(), "gif", arr);
}
else
{
error = "不支持该文件格式。";
return "错";
}
}
//}
//catch (Exception ex)
//{
// error = "生成图片发生错误。" + ex.ToString();
// return "错";
//}
}
#endregion
#region 保存图片路径及设置名称
/// <summary>
/// 保存到文件路径
/// </summary>
/// <param name="ImgName">保存的文件名称</param>
/// <param name="suffix">后缀名</param>
/// <param name="arr">base64</param>
/// <returns>图片的路径</returns>
public string SetImg(string ImgName, string suffix, byte[] arr)
{
string str3 = System.AppDomain.CurrentDomain.BaseDirectory;//找到相对路径
string str4 = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase;//找到相对路径
System.IO.File.WriteAllBytes(str3 + "/Upload/Article/" + ImgName + "." + suffix + "", arr);
return "/Upload/Article/" + ImgName + "." + suffix + "";
}
#endregion
#endregion