2013-11-22 52 views
0

我有一个函数,它可以接受图像并调整它的大小以适合画布,同时保持其纵横比。此代码只能从这个答案代码的minorly修改后的版本:c# Image resizing to different size while preserving aspect ratioGraphics.DrawImage不改变图像的大小

在这个例子中,我的画布高度是642,我的画布宽度为823

当我运行下面的功能,线路

graphic.DrawImage(image, posX, posY, newWidth, newHeight); 

貌似对图像大小没有影响。在场地状况:

Image.Height == 800, 
Image.Width == 1280. 
newHeight = 514, 
newWidth == 823 

运行后graphic.DrawImage

Image.Height == 800, 
Image.Width == 1280. 

正如你所看到的,图像的高度和宽度都不变。

有没有人看到一个明显的错误会导致这种情况发生?谢谢!

private Bitmap resizeImage(Bitmap workingImage, 
         int canvasWidth, int canvasHeight) 
    { 
     Image image = (Bitmap)workingImage.Clone(); 

     System.Drawing.Image thumbnail = 
      new Bitmap(canvasWidth, canvasHeight); 

     double ratioX = (double)canvasWidth/(double)workingImage.Width; 
     double ratioY = (double)canvasHeight/(double)workingImage.Height; 

     double ratio = ratioX < ratioY ? ratioX : ratioY; 

     int newHeight = Convert.ToInt32((double)workingImage.Height * ratio); 
     int newWidth = Convert.ToInt32((double)workingImage.Width * ratio); 

     int posX = Convert.ToInt32((canvasWidth - ((double)workingImage.Width * ratio))/2); 
     int posY = Convert.ToInt32((canvasHeight - ((double)workingImage.Height * ratio))/2); 

     using (Graphics graphic = Graphics.FromImage(thumbnail)) 
     { 
      graphic.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; 
      graphic.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; 
      graphic.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality; 
      graphic.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality; 

      graphic.Clear(SystemColors.Control); 
      graphic.DrawImage(image, posX, posY, newWidth, newHeight); //<--- HERE 
     } 

     System.Drawing.Imaging.ImageCodecInfo[] info = 
         System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders(); 
     System.Drawing.Imaging.EncoderParameters encoderParameters; 
     encoderParameters = new System.Drawing.Imaging.EncoderParameters(1); 
     encoderParameters.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 
         100L); 

     return workingImage; 
    } 
+0

我觉得POSX和波西应该是两个0 - 你开始新鲜的,所以你要填补整个地区。缩略图应该使用新的尺寸创建,而不是原始的(不是canvasW和canvasH)。 – pasty

回答

5

图像的大小为这里

Image image = (Bitmap)workingImage.Clone(); 

定义这

graphic.DrawImage(image, posX, posY, newWidth, newHeight); 

只有指定的参数绘制图像,但并不意味着图像尺寸得到改变。换句话说,绘制图像根本不会改变其大小,只是将图像放在画布上并根据需要绘制。

+0

当然!图形保存到缩略图中,而不是图像。男人,我不是愚蠢就是累了。不能相信我错过了那个= D 非常感谢您的帮助! –