调整图像大小保持高宽比白线边框
问题描述:
使用下面的代码(改编自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:
样本调整后的图像
放大中在角落显露白色边框
答
试图改变线路
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
'float'可能是导致计算为1个像素短。更改'float'为'double' –
@BarmakShemirani谢谢...其实下面的答案解决了这个问题.. – techno