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
目录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
- Random image website: https://picsum.photos/
- How to use ImageSharp for image generation in .NET Core: https://www.cnblogs.com/niwan/p/11126239.html
- https://stackoverflow.com/questions/63639644/how-load-an-image-from-disk-and-save-to-a-stream-using-imagesharp-while-preservi
_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 分钟
方便的C#-Json库:Json-Net
官网 Json.Net用法很简单,本文也只是搬运了一下官网的例子,更多用法可以查看官网,一分钟就能上手。 https://www.newtonsoft.com/json 使用例子 对象序列化 Product product = new Product(); product.Name = Apple; product.Expiry = new DateTime(2008, 12, 28); prod
2022-05-27 · C# · 约 1 分钟
Spark.NET:一个试图把 Django / Rails 式开发体验带回 .NET 世界的全栈 Web 框架。
又一个把Django/Rails那套“约定优于配置”搬进.NET生态的尝试,看着有点意思。预置了认证、队列、定时任务这些破事,省得自己天天重复造轮子。但767个star连个正式release都没有,就敢打着“生产级”旗号?呵,C#全栈爱好者们可以先玩玩,但别指望它能替代ASP.NET Core的体量。
2026-04-29 · C# · 约 1 分钟
C# 扩展方法只会写 this 吗?C# 14 新语法直接把扩展方法玩出了花
.NET 10 的扩展方法语法糖?哦,用 `extension` 块定义扩展,支持属性和方法了,以前不行,现在行,真稀奇。静态扩展成员?太晚了点,给 `DateTime` 添加静态方法,终于能优雅了。升级吧,不然怎么享受这些新玩具?
2026-03-05 · C# · 约 1 分钟
讨论
共 0 条加载评论中…