/// <summary>
/// 訪問圖片
/// </summary>
/// <param name="width">所訪問圖片的寬度,高度自動縮放,大於原圖尺寸或者小於等於0返回原圖</param>
/// <param name="name">所要訪問圖片的名稱或者相對地址</param>
/// <returns>圖片</returns>
[HttpGet]
[Route("{width}/{name}")]
public IActionResult GetImage(int width, string name)
{
//尋找Json配置文件中的路徑
var appPath = AppSettingHelper.GetConfig("PicturePath");
var errorImage = appPath + "404.png";//沒有找到圖片
var imgPath = string.IsNullOrEmpty(name) ? errorImage : appPath + name;
//獲取圖片的返回類型
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)
{
using (var sw = new FileStream(imgPath, FileMode.Open))
{
var bytes = new byte[sw.Length];
sw.Read(bytes, 0, bytes.Length);
sw.Close();
return new FileContentResult(bytes, contentTypeStr);
}
}
//縮小圖片
using (var imgBmp = new 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 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);
}
}
.Net Core訪問服務端圖片API(設置訪問圖片名稱及尺寸)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.