我有这个代码来调整位图的大小,但它所做的只是裁剪它而不是调整大小,我做错了什么?
public static System.Drawing.Bitmap ResizeImage(System.Drawing.Image image, int width, int height)
{
//a holder for the result
Bitmap result = new Bitmap(width, height);
// set the resolutions the same to avoid cropping due to resolution differences
result.SetResolution(image.HorizontalResolution, image.VerticalResolution);
//use a graphics object to draw the resized image into the bitmap
using (Graphics graphics = Graphics.FromImage(result))
{
//set the resize quality modes to high quality
graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
//draw the image into the target bitmap
graphics.DrawImage(image, 0, 0, result.Width, result.Height);
}
//return the resulting bitmap
return result;
}
我打电话给这个函数
bmPhoto = Imaging.ImageProcessing.ResizeImage(bmPhoto, scaledSize.Width, scaledSize.Height);
答案 0 :(得分:1)
尝试使用Rectangle
对象指定要填充的新图像部分,如下所示:
graphics.DrawImage(image, new Rectangle(0, 0, result.Width, result.Height), 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, null);
如上所述,Rectangle
指定应在左上角和右下角之间绘制图像,然后提供要缩放到该区域的原始图像的坐标({{1} })。
答案 1 :(得分:1)
// Keeping Aspect Ratio
Image resizeImg(Image img, int width)
{
double targetHeight = Convert.ToDouble(width) / (img.Width / img.Height);
Bitmap bmp = new Bitmap(width, (int)targetHeight);
Graphics grp = Graphics.FromImage(bmp);
grp.DrawImage(img, new Rectangle(0, 0, bmp.Width, bmp.Height), new Rectangle(0, 0, img.Width, img.Height), GraphicsUnit.Pixel);
return (Image)bmp;
}
// Without Keeping Aspect Ratio
Image resizeImg(Image img, int width, int height)
{
Bitmap bmp = new Bitmap(width, height);
Graphics grp = Graphics.FromImage(bmp);
grp.DrawImage(img, new Rectangle(0, 0, bmp.Width, bmp.Height), new Rectangle(0, 0, img.Width, img.Height), GraphicsUnit.Pixel);
return (Image)bmp;
}