2012-04-26 27 views
4

我有一个很大的图像,我想调整大小为230×320(正好)。我希望系统调整大小而不会损失宽高比。即如果图像是460×650,则应首先调整至230×325,然后裁剪额外5个像素的高度。使用ImageMagick.NET和C调整作物大小#

我做了以下内容:

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

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

我在C#4.0中使用ImageMagick.NET

回答

5

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

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 2014-01-08 13:37:14