2013-11-22 96 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 非常感謝您的幫助! –