曦远 (DealiAxy)一份私人的文字刊物

StarBlog
返回文章列表折页手记阅读全文
C#

Implementing Image Scaling and Cropping in .NET Core - Based on ImageSharp

Preface ~~(Suddenly realized I haven't updated in a while~~ Recently while working on my blog, I needed to implement a random image feature similar to Lorempixel and LoremPicsum. I already had the images, and I also needed a feature to get an image based on the input width and height. Since I had used the ImageSharp library when processing images before, I immediately thought of using it this time. Analyzing Requirements The images in the image library are basically wallpapers I collected before, with uneven sizes, some landscape and some portrait Then wrapping it as an API that only requires inputting width and height, can

曦远 (DealiAxy)约 9 分钟
目录5 个章节

Preface

(Suddenly realized I haven't updated in a while

Recently while working on my blog, I needed to implement a random image feature similar to Lorempixel and LoremPicsum. I already had the images, and I also needed a feature to get an image based on the input width and height. Since I had used the ImageSharp library when processing images before, I immediately thought of using it this time.

Analyzing Requirements

The images in the image library are basically wallpapers I collected before, with uneven sizes, some landscape and some portrait

Then wrapping it as an API that only requires inputting width and height, it can randomly pick an image and then scale or crop it

My approach is:

  • For landscape images, adjust the height to match the input height, and adjust the width proportionally
  • For portrait images, adjust the width to match the input height, and adjust the height proportionally

Then select the middle portion for cropping

Of course there's also a special case, when the input width and height exceed the original height and width of the image; in this case we can only break the original aspect ratio of the image and force a stretch~

PS: I originally wanted to draw a diagram to express the idea, but I couldn't find a handy drawing tool (Draw.io: don't look at me)

Implementation

First, read the image

Very simple, just pass in the image path

Of course you can also read it via a stream

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

Then, based on the various size cases of the image, perform scaling and cropping

A lot of the blog posts I found online use code similar to image.Resize and image.Crop, but this is the old version of ImageSharp code

In the new version everything is placed in image.Mutate, and you pass in a lambda expression for whatever operation you need

(A bit like ORM operations)

For example, scaling looks like this

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

Cropping looks like this

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

Complete Code

The functionality is very simple; the complete code is here

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");
}

Follow-up will be updated in my StarBlog development notes series~

References

_EOF_

Implementing Image Scaling and Cropping in .NET Core - Based on ImageSharp

本文作者:
程序设计实验室
版权声明:
本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!

相关文章

System.Text.Json使用中的几个常见问题

前言 以前.NetCore是不内置JSON库的,所以大家都用Newtonsoft的JSON库,而且也确实挺好用的,不过既然官方出了标准库,那更方便更值得我们多用用,至少不用每次都nuget安装Newtonsoft.Json库了。 不过日常开发使用中会有一些问题,本文记录一下解决方法,欢迎交流~ ~~(文章末尾包含小彩蛋)~~ 字符编码问题 默认的 System.Text.Json 序列化的时候会把

2022-05-27 · C# · 约 1 分钟

讨论

共 0 条

良言一句三冬暖,恶语伤人六月寒。

加载评论中…