Resize with crop using ImageMagick.NET and C#

空扰寡人 提交于 2019-12-09 18:25:50

问题


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.

I am doing the following:

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

But the images are not being resized to the exact size 230×320.

I am using ImageMagick.NET in C# 4.0.


回答1:


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


来源:https://stackoverflow.com/questions/10337800/resize-with-crop-using-imagemagick-net-and-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!