using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Drawing;
using System.Drawing.Imaging;
using System.Web.Hosting;
namespace TF.Common
{
public class UploadImage
{
/// <summary>
/// 将Base64位码保存成图片
/// </summary>
/// <param name="UserPhoto">Base64位码</param>
/// <returns></returns>
public static string UploadImageByBase64String(string UserPhoto)
{
//if (!ModelState.IsValid)
//{
// LogHelper.WriteLog(ErrorPrompt.ValidationFailure);
// return BadRequest(ModelState);
//}
string result;
//图片路径
string filePath = HttpContext.Current.Server.MapPath("~/" + @System.Configuration.ConfigurationManager.AppSettings["ImagePath"]);
try
{
byte[] bt = Convert.FromBase64String(UserPhoto);//获取图片base64
string fileName = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString();//年月
string ImageFilePath = "/Image" + "/" + fileName;
if (System.IO.Directory.Exists(HttpContext.Current.Server.MapPath(ImageFilePath)) == false)//如果不存在就创建文件夹
{
System.IO.Directory.CreateDirectory(HttpContext.Current.Server.MapPath(ImageFilePath));
}
string ImagePath = HttpContext.Current.Server.MapPath(ImageFilePath) + "/" + System.DateTime.Now.ToString("yyyyHHddHHmmss");//定义图片名称
File.WriteAllBytes(ImagePath + ".jpg", bt); //保存图片到服务器,然后获取路径
result = ImagePath + ".jpg";//获取保存后的路径
}
catch (Exception e)
{
throw e;
}
//LogHelper.WriteLog(ErrorPrompt.Success);
return result;
}
//用这个
//用List集合保存传递过来的Base654格式的图片,前端是用数组存图片进行发送后端的
//传递的是一个Data对象,我的控制器也用对象类型接受
public static string UpLoadImg(string file)
{
//前端传递的data里的key必须和后台类里的字段保持一致,否则接受不到前端传递的数据
//List<string> imgInfoList = funnyInfo.image;
//string guids = funnyInfo.guid;
if (file != null)
{
//图片保存的路径
string imgPath = HostingEnvironment.MapPath("~/img/");
string path="";
string pathTwo = "";
if (!Directory.Exists(imgPath))
{
Directory.CreateDirectory(imgPath);
}
else
{
Guid guid = Guid.NewGuid();
//将图片保存为jpg格式,图片名为guid.jpg
path = guid + ".jpg";
//调用方法解析Base64编码的图片,并保存图片
Base64ToImg(file.Split(',')[1]).Save(imgPath + path);
pathTwo = "/img/"+ path;
}
return pathTwo;
}
else
{
return "-1";
}
}
//解析base64编码获取图片
private static Bitmap Base64ToImg(string base64Code)
{
MemoryStream stream = new MemoryStream(Convert.FromBase64String(base64Code));
return new Bitmap(stream);
}
}
}
Upload picture (file stream)
Guess you like
Origin blog.csdn.net/qq_39072819/article/details/102661402
Recommended
Ranking