2016-07-29 150 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

相关问题