我正在尝试将图片大小调整为500x500像素。使用以下代码:
public static Bitmap ResizeImage(System.Drawing.Image image, int width, int height)
{
var destRect = new Rectangle(0, 0, width, height);
var destImage = new Bitmap(width, height);
destImage.SetResolution(image.HorizontalResolution, image.VerticalResolution);
using (var graphics = Graphics.FromImage(destImage))
{
graphics.CompositingMode = CompositingMode.SourceCopy;
graphics.CompositingQuality = CompositingQuality.HighQuality;
graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
graphics.SmoothingMode = SmoothingMode.HighQuality;
graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
using (var wrapMode = new ImageAttributes())
{
wrapMode.SetWrapMode(WrapMode.TileFlipXY);
graphics.DrawImage(image, destRect, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, wrapMode);
}
}
return destImage;
}
但这只是横向调整大小而不是裁剪!有人建议我将图像裁剪为居中的1:1比例,然后缩小比例。 如果图像小于它,我也希望将图像尺寸增加到500x500。
我怎样才能实现它?
答案 0 :(得分:1)
而不是
using (var wrapMode = new ImageAttributes())
{
wrapMode.SetWrapMode(WrapMode.TileFlipXY);
graphics.DrawImage(image, destRect, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, wrapMode);
}
使用
Rectangle cropRect = new Rectangle(0,0,500,500);
graphics.DrawImage(image, destRect, cropRect, GraphicsUnit.Pixel);
您还可以阅读有关DrawImageUnscaledAndClipped
的更多信息,以便进行裁剪。