C Sharper
C Sharper

Reputation: 8626

Resize image in asp.net Size readonly error

I want to resize the image coming through file uploader. For that I was referred to the following:

How to set Bitmap.Width and Bitmap.height

(Javed Akram's Answer)

Made following code:

Dim imgSmall As Bitmap = New Bitmap(FUpload.PostedFile.InputStream, False)
imgSmall.Size = New Size(250, 300)

But giving me error:

Size is read-only property.

How can I resize the image in this case?

Upvotes: 0

Views: 1497

Answers (1)

sh1rts
sh1rts

Reputation: 1884

It is read-only; you'll have to create a new bitmap from it. Try this: -

internal static Image ScaleByPercent(Image image, Size size, float percent)
{
    int sourceWidth  = image.Width,
        sourceHeight = image.Height;

    int destWidth  = (int)(sourceWidth * percent),
        destHeight = (int)(sourceHeight * percent);

    if (destWidth <= 0)
    {
        destWidth = 1;
    }

    if (destHeight <= 0)
    {
        destHeight = 1;
    }

    var resizedImage = new Bitmap(destWidth, destHeight, PixelFormat.Format24bppRgb);
    resizedImage.SetResolution(image.HorizontalResolution, image.VerticalResolution);

    // get handle to new bitmap
    using (var graphics = Graphics.FromImage(resizedImage))
    {
        InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;

        // create a rect covering the destination area
        var destRect = new Rectangle(0, 0, destWidth, destHeight);
        var brush    = new SolidBrush(drawing.Color.White);
        graphics.FillRectangle(brush, destRect);

        // draw the source image to the destination rect
        graphics.DrawImage(image,
                            destRect,
                            new Rectangle(0, 0, sourceWidth, sourceHeight),
                            GraphicsUnit.Pixel);
    }

    return resizedImage;
}

This is from a site I have in production; if you want I can send you the code that works out how to keep the correct aspect ratio when resizing (i.e. what gets passed in the 'size' parameter)

Hope that helps

Upvotes: 2

Related Questions