Search code examples
c#imageresizepicturebox

Resize a PictureBox


I want to show a Resized Picture in my Picturebox. The original picture is: enter image description here And the Picture in my form: enter image description here

My picturebox size is 500x500px. My method that I use for the resize:

    public static Image ResizePicByWidth(Image sourceImage, double newWidth)
    {
        double sizeFactor = newWidth / sourceImage.Width;
        double newHeigth = sizeFactor * sourceImage.Height;
        Bitmap newImage = new Bitmap((int)newWidth, (int)newHeigth);
        using (Graphics g = Graphics.FromImage(newImage))
        {
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
            g.DrawImage(sourceImage, new Rectangle(0, 0, (int)newWidth, (int)newHeigth));
        }
        return newImage;
    }

I call the method with the original picture and the width from the picturebox. But how can i resize the picture correctly? I want my Form to show the whole Picture.


Solution

  • PictureBox has a SizeMode property. If you set this to Zoom it will automatically resize the image in it to fit inside it.