使用ImageMagick.NET和C#进行裁剪调整大小

10

我有一张大图像,想将其缩放到230×320(精确尺寸)。我希望系统在调整大小时不会失去宽高比。例如,如果图像的尺寸是460×650,则应先将其缩放到230×325,然后裁剪高度多余的5个像素。

我正在执行以下操作:

ImageMagickNET.Geometry geo = new ImageMagickNET.Geometry("230x320>");
img.Resize(geo);

然而,这些图像尺寸并未被准确调整为230×320。

我正在使用C# 4.0中的ImageMagick.NET

1个回答

13

这是我解决问题的方式。

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

1
谢谢Tony!我一直在寻找解决这个问题的方法,所有的答案都与命令行工具有关。很高兴知道还有其他人也在使用.NET API。 - Mark

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接