6

.NetCore实现图片缩放与裁剪 - 基于ImageSharp - 程序设计实验室

 2 years ago
source link: https://www.cnblogs.com/deali/p/16387392.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

.NetCore实现图片缩放与裁剪 - 基于ImageSharp - 程序设计实验室 - 博客园

(突然发现断更有段时间了

最近在做博客的时候,需要实现一个类似Lorempixel、LoremPicsum这样的随机图片功能,图片有了,还需要一个根据输入的宽度高度获取图片的功能,由于之前处理图片时使用到了ImageSharp库,所以这次我立刻就想到用它。

图片库中的图片基本都是我之前收集的壁纸什么的,尺寸参差不齐,有横屏的也有竖屏

然后包装成接口只需要输入宽度和高度,就能随机选一张图片然后进行缩放或者裁剪

我的思路是:

  • 横屏图片,将高度调整到与输入高度一致,宽度按比例调整
  • 竖屏图片,将宽度调整到与输入高度一致,高度按比例调整

然后再选取中间部分进行截取

当然还有特殊情况,就是输入的宽度和高度超过图片原来高度宽度的情况,这个只能破坏图片原有的比例,强行进行拉伸~

PS:本来想画个图表达一下思路,不过没找到趁手的画图工具(Draw.io:不要看我)

首先读取图片

很简单,传入图片路径即可

当然也可以用流的方式读取

using var image = Image.Load("imagePath");

然后就是根据图片的大小各种情况来进行缩放和裁剪

在网上查到的很多博客用的代码都是类似image.Resizeimage.Crop之类的,但这是旧版的ImageSharp代码

新版全都放在image.Mutate里,要什么操作再传入lambda表达式

(有点像ORM的操作)

比如缩放就是这样

image.Mutate(a => a.Resize(newWidth, newHeight));

裁剪就是这样

image.Mutate(a => a.Crop(new Rectangle(x, y, width, height)));

功能很简单,完整代码在此

void GetImage(string imagePath, int width, int height) {
    using var image = Image.Load(imagePath);
    Rectangle cropRect;
    int newWidth;
    int newHeight;
    
    // 横屏图片
    if (image.Width > image.Height) {
        if (width > image.Width) {
            newWidth = width;
            newHeight = height;
        }
        else {
            newHeight = height;
            newWidth = image.Width / image.Height * newHeight;
        }

        cropRect = new Rectangle((newWidth - width) / 2, 0, width, height);
    }
    // 竖屏图片
    else {
        if (height > image.Height) {
            newWidth = width;
            newHeight = height;
        }
        else {
            newWidth = width;
            newHeight = newWidth * image.Height / image.Width;
        }

        cropRect = new Rectangle(0, (newHeight - height) / 2, width, height);
    }

    image.Mutate(a => a.Resize(newWidth, newHeight));
    image.Mutate(a => a.Crop(cropRect));
    image.SaveAsPng("output.png");
}

后续在我的StarBlog开发笔记系列里,接下来会更新~

__EOF__

本文作者: 程序设计实验室 本文链接: https://www.cnblogs.com/deali/p/16387392.html 关于博主: 公众号:程序设计实验室,欢迎交流~ 版权声明: 本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处! 声援博主: 如果您觉得文章对您有帮助,可以点击文章右下角推荐一下。

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK