背景: .net core 中默认已经取消可以直接访问图片,因为这样不安全. 导致我们上传的图片无法直接通过url访问.
解决方案:
一: 通过修改项目配置,使可以直接通过url访问.(方法略,可以百度);
二: 图片都通过接口返回,接口里面读取项目的图片,然后返回流;
步骤:
1.新建.net core 2.0 项目(过程略)
2.通过nuget添加引用 System.Drawing.Common; .net core 开始的时候并没有System.Drawing,在2.0之后新增了 System.Drawing.Common,用于替代原来的System.Drawing.用法基本一致
3.写接口了
a. 使用特性路由传入想要的尺寸和文件名,这样可以更好的用于前端展示,
b. 没有找到图片或者错误时返回默认的一张图片
c. 需要注意引用 using System.IO;using System.Drawing;
d. .net core 中返回图片不用 HttpResponseMessage 类型,而是直接采用 IActionResult. 而且封装了FileContentResult类,可以直接返回.
e. .net core 中获取当前项目的物理地址可以通过 AppContext.BaseDirectory 和.net 有区别
///
///访问图片///
/// 所访问图片的宽度,高度自动缩放,大于原图尺寸或者小于等于0返回原图
/// 所要访问图片的名称或者相对地址
/// 图片
[HttpGet]
[Route("file/image/{width}/{name}")]public IActionResult GetImage(int width, stringname)
{var appPath = AppContext.BaseDirectory.Split("\\bin\\")[0] + "/image/";var errorImage = appPath + "404.png";//没有找到图片
var imgPath = string.IsNullOrEmpty(name) ? errorImage : appPath +name;//获取图片的返回类型
var contentTypDict = new Dictionary{
{"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//vnd.wap.wbmp"},
{"rp","image/vnd.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 (!newFileInfo(imgPath).Exists)
{
imgPath=errorImage;
}//原图
if (width <= 0)
{using (var sw = newFileStream(imgPath, FileMode.Open))
{var bytes = new byte[sw.Length];
sw.Read(bytes,0, bytes.Length);
sw.Close();return newFileContentResult(bytes, contentTypeStr);
}
}//缩小图片
using (var imgBmp = newBitmap(imgPath))
{//找到新尺寸
var oWidth =imgBmp.Width;var oHeight =imgBmp.Height;var height =oHeight;if (width >oWidth)
{
width=oWidth;
}else{
height= width * oHeight /oWidth;
}var newImg = newBitmap(imgBmp, width, height);
newImg.SetResolution(72, 72);var ms = newMemoryStream();
newImg.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);var bytes =ms.GetBuffer();
ms.Close();return newFileContentResult(bytes, contentTypeStr);
}
}
4.结果如下图
700px 宽度
200px 宽度
附:.NET Core项目在Linux上使用QRCoder时出错"Unable to load DLL 'gdiplus'" 解决方法(安装按记得重启netcore程序)
方法一:
yum install libgdiplus-devel
如果提示“No package libgdiplus-devel available.”,看下面网址
https://www.cnblogs.com/wintertone/p/12936552.html
方法二:
1) apt install libgdiplus
2) cp /usr/lib/libgdiplus.so ~/.nuget/packages/qrcoder/1.3.1/lib/netstandard2.0
https://www.cnblogs.com/fancyblogs/p/9822132.html
https://q.cnblogs.com/q/98966/
本文介绍了如何在ASP.NET Core 2.0中创建一个接口来返回并根据需求压缩图片。通过添加System.Drawing.Common引用,实现读取项目中的图片,并根据传入的宽度参数调整图片尺寸。当图片不存在或格式不正确时返回默认图片。同时,文章还提到了.NET Core在Linux环境下使用QRCoder库时可能出现的问题及解决方法。
489

被折叠的 条评论
为什么被折叠?



