9

我有一个大图像,我想将其调整为 230×320(精确)。我希望系统在不丢失纵横比的情况下调整它的大小。即如果图像是 460×650,它应该首先调整到 230×325,然后裁剪额外的 5 个像素的高度。

我正在执行以下操作:

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

但是图像并没有被调整到 230×320 的精确尺寸。

我在 C# 4.0 中使用ImageMagick.NET 。

4

1 回答 1

10

这就是我解决问题的方法。

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);
    }
于 2012-04-30T15:10:19.410 回答