使用ImageMagick.NET和C#调整裁剪大小 [英] Resize with crop using ImageMagick.NET and C#
本文介绍了使用ImageMagick.NET和C#调整裁剪大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一张大图像,想要调整为230×320(正好).我希望系统在不损失宽高比的情况下调整其大小.也就是说,如果图片的尺寸为460×650,则应首先将其尺寸调整为230×325,然后再裁剪另外5个像素的高度.
I have a big image that I want to resize to 230×320 (exactly). I want the system to resize it without losing aspect ratio. i.e. if the image is 460×650, it should first resize to 230×325 and then crop the extra 5 pixels of height.
我正在执行以下操作:
ImageMagickNET.Geometry geo = new ImageMagickNET.Geometry("230x320>");
img.Resize(geo);
但是图像没有被调整为230×320的确切尺寸.
But the images are not being resized to the exact size 230×320.
我在C#4.0中使用 ImageMagick.NET .
I am using ImageMagick.NET in C# 4.0.
推荐答案
这就是我解决问题的方式.
This is how I solved the issue.
private void ProcessImage(int width, int height, String filepath)
{
// FullPath is the new file's path.
ImageMagickNET.Image img = new ImageMagickNET.Image(filepath);
String file_name = System.IO.Path.GetFileName(filepath);
if (img.Height != height || img.Width != width)
{
decimal result_ratio = (decimal)height / (decimal)width;
decimal current_ratio = (decimal)img.Height / (decimal)img.Width;
Boolean preserve_width = false;
if (current_ratio > result_ratio)
{
preserve_width = true;
}
int new_width = 0;
int new_height = 0;
if (preserve_width)
{
new_width = width;
new_height = (int)Math.Round((decimal)(current_ratio * new_width));
}
else
{
new_height = height;
new_width = (int)Math.Round((decimal)(new_height / current_ratio));
}
String geomStr = width.ToString() + "x" + height.ToString();
String newGeomStr = new_width.ToString() + "x" + new_height.ToString();
ImageMagickNET.Geometry intermediate_geo = new ImageMagickNET.Geometry(newGeomStr);
ImageMagickNET.Geometry final_geo = new ImageMagickNET.Geometry(geomStr);
img.Resize(intermediate_geo);
img.Crop(final_geo);
}
img.Write(txtDestination.Text + "\\" + file_name);
}
这篇关于使用ImageMagick.NET和C#调整裁剪大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文