Mario
Mario

Reputation: 14760

Bitmap Resize, only crops the image and no resizing

I have this code to resize a bitmap, but all it does is to crop it instead of resizing, what I am doing wrong?

    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;
    }

and I call the function like this

bmPhoto = Imaging.ImageProcessing.ResizeImage(bmPhoto, scaledSize.Width, scaledSize.Height);

Upvotes: 0

Views: 1763

Answers (2)

Abdul Saleem
Abdul Saleem

Reputation: 10612

// 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;

}

Upvotes: 1

Maloric
Maloric

Reputation: 5605

Try using a Rectangle object to specify the portion of the new image that you want to fill, like so:

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

As noted the Rectangle specifies that the image should be drawn between the top left and bottom right corner, and then you provide the coordinates of the original image that you want to scale into that area (0,0,image.Width,image.Height).

Upvotes: 1

Related Questions