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 许可协议。转载请注明出处!
相关文章
C#中的Attribute与Python-TypeScript的装饰器是同个东西吗
前言 最近成功把「前端带师」带入C#的坑~~(实际是前端带师开始从cocos转unity游戏开发了)~~ 某天,「前端带师」看到这段代码后问了个问题:[这个是装饰器]? [HttpGet] public Response Get() { return ... } 我第一反应觉得不是,这玩意在C#中叫“特性”(英文名Attribute,下文统称为特性),在Java中叫注解,虽然写法和Pyth
2022-06-26 · C# · 约 1 分钟
C#实现生成Markdown文档目录树
前言 之前我写了一篇关于C#处理Markdown文档的文章:C#解析Markdown文档,实现替换图片链接操作 算是第一次尝试使用C#处理Markdown文档,然后最近又把博客网站的前台改了一下,目前文章渲染使用Editor.md组件在前端渲染,但这个插件生成的目录树很丑,我魔改了一下换成bootstrap5-treeview组件,好看多了。详见这篇文章:魔改editormd组件,优化ToC渲染效
2022-10-26 · C# · 约 1 分钟
使用C#和MemoryCache组件实现轮流调用APIKey以提高并发能力
本文介绍了如何利用C#语言中的MemoryCache组件,结合并发编程技巧,实现轮流调用多个API Key以提高系统的并发能力。通过示例代码和详细说明,读者将了解如何有效地管理API Key的调用次数限制,并优化系统性能。
2024-03-09 · C# · 约 1 分钟
C#高性能数组拷贝实验
前言 昨天 wc(Wyu_Cnk) 提了个问题 C# 里多维数组拷贝有没有什么比较优雅的写法? 这不是问对人了吗?正好我最近在搞图像处理,要和内存打交道,我一下就想到了在C#里面直接像C/C++一样做内存拷贝。 优雅?no,要的就是装逼,而且性能还要强🕶 概念 首先澄清一下 C# 里的多维数组 (Multi-dimensional Array) 是这样的 byte[,] arr = new by
2023-01-30 · C# · 约 1 分钟
讨论
共 0 条加载评论中…