在做项目中需要实现通过API上传图片,并将图片保存至服务器指定的文件夹下。
具体实现思路:
1.将图片转换为Base64数据传递给API
//读取图片转码Base64并上传服务器
FileStream fs = new FileStream(Imagepath, FileMode.Open);//Imagepath图片路径
byte[] byteData = new byte[fs.Length];
fs.Read(byteData, 0, byteData.Length);
fs.Close();
String data=Convert.ToBase64String(byteData);//转换Base64
2.API获取到数据后转换为图片存储到本地
/// <summary>
/// 将Base64图片数据存入指定路径
/// </summary>
/// <param name="fileBase64">Base64图片数据</param>
/// <param name="fileName">图片名</param>
/// <param name="imagePath">保存路径</param>
/// <returns></returns>
public static string UploadBase64(string fileBase64, string fileName,string imagePath)
{
byte[] bytes = Convert.FromBase64String(fileBase64);
var fileExtension = Path.GetExtension(fileName);
var strDateTime = DateTime.Now.ToString("yyMMddhhmmssfff"); //取得时间字符串
var strRan = Convert.ToString(new Random().Next(100, 999)); //生成三位随机数
var saveName = strDateTime + strRan + fileExtension;
//var savePath = @"./Images/" + saveName+".jpg";E:/Images/
var savePath = imagePath + saveName + ".jpg";
try
{
Image image1 = BytesToImage(bytes); //byte[]转换为图片
System.Drawing.Bitmap image = new System.Drawing.Bitmap(image1);
//string imgname = DateTime.Now.ToString("yyyyMMddhhmmss") + ".jpg";
//string path = "~/images/" + imgname;
image.Save(savePath);
return saveName;
}
catch (Exception ex)
{
//WriteSysLog(ex.ToString(), Entity.Base_SysManage.EnumType.LogType.接口调用异常);
return "错误";
}
}
3.将图片路径存到数据库,通过图片路径地址获取图片
/// <summary>
/// 访问图片
/// </summary>
/// <param name="width">所访问图片的宽度,高度自动缩放,大于原图尺寸或者小于等于0返回原图</param>
/// <param name="imgPath ">所要访问图片的名称或者相对地址</param>
/// <returns>图片</returns>
[HttpGet]
public IActionResult GetImage(int width,string imgPath )
{
//获取图片的返回类型
var contentTypDict = new Dictionary<string, string> {
{"jpg","image/jpeg"},
{"jpeg","image/jpeg"},
{"jpe","image/jpeg"},
{"png","image/png"},
{"gif","image/gif"},
{"ico","image/x-ico"},
{"tif","image/tiff"},
{"tiff","image/tiff"},
{"fax","image/fax"},
{"wbmp","image/nd.wap.wbmp"},
{"rp","imagend.rn-realpix"}
};
var contentTypeStr = "image/jpeg";
var imgTypeSplit = name.Split('.');
var imgType = imgTypeSplit[imgTypeSplit.Length - 1].ToLower();
//未知的图片类型
if (!contentTypDict.ContainsKey(imgType))
{
imgPath = errorImage;
}
else
{
contentTypeStr = contentTypDict[imgType];
}
//图片不存在
if (!new FileInfo(imgPath).Exists)
{
imgPath = errorImage;
}
//原图
if (width <= 0)
{
//try
//{
using (var sw = new FileStream(imgPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
var bytes = new byte[sw.Length];
sw.Read(bytes, 0, bytes.Length);
sw.Close();
return new FileContentResult(bytes, contentTypeStr);
}
//}
//catch(Exception ex)
//{
//}
}
//缩小图片
using (var imgBmp = new System.Drawing.Bitmap(imgPath))
{
//找到新尺寸
var oWidth = imgBmp.Width;
var oHeight = imgBmp.Height;
var height = oHeight;
if (width > oWidth)
{
width = oWidth;
}
else
{
height = width * oHeight / oWidth;
}
var newImg = new System.Drawing.Bitmap(imgBmp, width, height);
newImg.SetResolution(72, 72);
var ms = new MemoryStream();
newImg.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
var bytes = ms.GetBuffer();
ms.Close();
return new FileContentResult(bytes, contentTypeStr);
}
}