2016-07-29 140 views
0

使用下面的代碼(改編自Example #2 here)調整圖像大小以保持縱橫比。但是我一直在調整大小的圖像周圍出現白色邊框。我做錯了什麼。調整圖像大小保持高寬比白線邊框

Bitmap ResizekeepAspectRatio(Bitmap imgPhoto, int Width, int Height) 
      { 
       int sourceWidth = imgPhoto.Width; 
       int sourceHeight = imgPhoto.Height; 
       int sourceX = 0; 
       int sourceY = 0; 
       int destX = 0; 
       int destY = 0; 

       float nPercent = 0; 
       float nPercentW = 0; 
       float nPercentH = 0; 

       nPercentW = ((float)Width/(float)sourceWidth); 
       nPercentH = ((float)Height/(float)sourceHeight); 
       if (nPercentH < nPercentW) 
       { 
        nPercent = nPercentH; 
        destX = System.Convert.ToInt16((Width - 
            (sourceWidth * nPercent))/2); 
       } 
       else 
       { 
        nPercent = nPercentW; 
        destY = System.Convert.ToInt16((Height - 
            (sourceHeight * nPercent))/2); 
       } 

       int destWidth = (int)(sourceWidth * nPercent); 
       int destHeight = (int)(sourceHeight * nPercent); 

       Bitmap bmPhoto = new Bitmap(Width, Height, 
            PixelFormat.Format24bppRgb); 
       bmPhoto.SetResolution(imgPhoto.HorizontalResolution, 
           imgPhoto.VerticalResolution); 

       Graphics grPhoto = Graphics.FromImage(bmPhoto); 
       grPhoto.Clear(Color.White); 
       grPhoto.InterpolationMode = 
         InterpolationMode.HighQualityBicubic; 

       grPhoto.DrawImage(imgPhoto, 
        new Rectangle(destX, destY, destWidth, destHeight), 
        new Rectangle(sourceX, sourceY, sourceWidth, sourceHeight), 
        GraphicsUnit.Pixel); 

       grPhoto.Dispose(); 
       return bmPhoto; 
      } 

UPDATE:

樣本調整後的圖像

enter image description here

放大中在角落顯露白色邊框

enter image description here

+0

'float'可能是導致計算爲1個像素短。更改'float'爲'double' –

+0

@BarmakShemirani謝謝...其實下面的答案解決了這個問題.. – techno

回答

1

試圖改變線路

Bitmap bmPhoto = new Bitmap(Width, Height, 
           PixelFormat.Format24bppRgb); 
To 
Bitmap bmPhoto = new Bitmap(destWidth, destHeight, 
          PixelFormat.Format24bppRgb); 

既然你想保持縱橫比你們中的大多數最終將不得不在圖像周圍多餘的空間的時候,所以如果你不需要額外的空間,然後使新的圖片大小適合新的目標大小

編輯:

Try to comment out the line grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic 
+0

謝謝..但我不是在談論額外的空間......我用另一個裁剪功能來裁剪關於圖像中的白線邊界...你有沒有看到更新.. – techno

+0

嘗試註釋行grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic; –

+0

謝謝......它的工作原理是什麼?評論這條線會降低輸出圖像質量嗎? – techno

相關問題