.net core 接口返回图片并且进行压缩

背景:  .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 有区别

复制代码
        /// <summary>
        /// 访问图片
        /// </summary>
        /// <param name="width">所访问图片的宽度,高度自动缩放,大于原图尺寸或者小于等于0返回原图</param>
        /// <param name="name">所要访问图片的名称或者相对地址</param>
        /// <returns>图片</returns>
        [HttpGet]
        [Route("file/image/{width}/{name}")]
        public IActionResult GetImage(int width, string name)
        {
            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<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//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 (!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);
            }
        }
复制代码

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/

posted @   冬音  阅读(2606)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 通过 API 将Deepseek响应流式内容输出到前端
· AI Agent开发,如何调用三方的API Function,是通过提示词来发起调用的吗
点击右上角即可分享
微信分享提示