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#-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 分钟
C#实现解析Markdown文档并处理图片链接
前言 又是好久没写博客了 其实也不是没写,是最近在「做一个博客」,从2月21日开始,大概一个多星期的时间,疯狂刷进度,边写代码边写了一整系列的博客开发笔记,目前为止已经写了16篇了,然后上3月之后工作有点忙~~加上有点沉迷原神~~,然后进度就暂时慢下来了 事实证明做什么事情一旦停下来就会产生惰性,于是停了这么久,我终于下定决心继续更新! 这次开发的博客用的是C#语言,搭配.netcore技术栈;前
2022-03-19 · C# · 约 1 分钟
让 C# 也拥有 gofmt 般的体验:用 CSharpier + Roslyn 实现 csfmt
C# 代码长到像答辩?用 CSharpier 自动折行,再用 Roslyn 修正 K&R 花括号,Taskfile 一键收尾。再补上 format-check,省得 CI 反复制造 Git diff。两步流水线并非原生 gofmt,顺序和版本仍得老实锁住。
2026-10-22 · C# · 约 1 分钟
C#实现生成Markdown文档目录树
前言 之前我写了一篇关于C#处理Markdown文档的文章:C#解析Markdown文档,实现替换图片链接操作 算是第一次尝试使用C#处理Markdown文档,然后最近又把博客网站的前台改了一下,目前文章渲染使用Editor.md组件在前端渲染,但这个插件生成的目录树很丑,我魔改了一下换成bootstrap5-treeview组件,好看多了。详见这篇文章:魔改editormd组件,优化ToC渲染效
2022-10-26 · C# · 约 1 分钟
讨论
共 0 条加载评论中…