0

我有这段代码来调整位图的大小,但它所做的只是裁剪而不是调整大小,我做错了什么?

    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);
4

2 回答 2

1

尝试使用一个Rectangle对象来指定要填充的新图像部分,如下所示:

graphics.DrawImage(image, new Rectangle(0, 0, result.Width, result.Height), 0,  0, image.Width, image.Height, GraphicsUnit.Pixel, null);

如前所述,Rectangle指定应在左上角和右下角之间绘制图像,然后提供要缩放到该区域的原始图像的坐标 ( 0,0,image.Width,image.Height)。

于 2013-09-19T13:07:26.500 回答
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;

}
于 2013-09-19T13:16:09.760 回答