Daniel Lip
Daniel Lip

Reputation: 11335

How can I resize the image to fit the picturebox?

I'm trying to resize the image to fit the PictureBox size but it's not working. I added a method resizeImage but no matter what size I give the result is the same.

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void pictureBox1_Paint(object sender, PaintEventArgs e)
    {
        Bitmap myBitmap = CreateNonIndexedImage(new Bitmap(@"d:\drawplane1.jpg"));
        resizeImage(myBitmap, new Size(1, 1));

        // Draw myBitmap to the screen.
        e.Graphics.DrawImage(myBitmap, 0, 0, myBitmap.Width,
            myBitmap.Height);

        // Set each pixel in myBitmap to black.
        for (int Xcount = 0; Xcount < myBitmap.Width; Xcount++)
        {
            for (int Ycount = 0; Ycount < myBitmap.Height; Ycount++)
            {
                myBitmap.SetPixel(Xcount, Ycount, Color.Black);
            }
        }

        // Draw myBitmap to the screen again.
        e.Graphics.DrawImage(myBitmap, myBitmap.Width, 0,
            myBitmap.Width, myBitmap.Height);
    }

    public Bitmap CreateNonIndexedImage(Image src)
    {
        Bitmap newBmp = new Bitmap(src.Width, src.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);

        using (Graphics gfx = Graphics.FromImage(newBmp))
        {
            gfx.DrawImage(src, 0, 0);
        }

        return newBmp;
    }

    public static Image resizeImage(Image imgToResize, Size size)
    {
        return (Image)(new Bitmap(imgToResize, size));
    }
}

No mater what size I put in the line:

resizeImage(myBitmap, new Size(1, 1));

..the image is too big inside the pictureBox: I tried 10,10 then 1,1 for testing but it's not changing the image size.

Image in picturebox

This is the original image :

Original

Original image file : https://i.sstatic.net/6uFMo.jpg

Upvotes: 0

Views: 1762

Answers (3)

Gy&#246;rgy Kőszeg
Gy&#246;rgy Kőszeg

Reputation: 18023

Your code has two issues:

  • You don't use the SizeMode property
  • You draw the image in the Paint event instead of just setting the Image property

If you want to draw the image in Paint (eg. because it is an animation, whose frames are generated rapidly), then you don't need a PictureBox, a simple Panel will also do it.

But if you generate the image once, then just assign it to the Image property, set the SizeMode for scaling and PictureBox will care about the rest

Upvotes: 1

integer
integer

Reputation: 221

You can use the SizeMode property of PictureBox from Properties window and set its value to StrechImage

enter image description here

Upvotes: 2

msmolcic
msmolcic

Reputation: 6577

Try setting the SizeMode of your PictureBox to PictureSizeMode.Zoom or PictureSizeMode.StretchImage and see if it helps. Either through your properties editor or in code.

 pictureBox1.SizeMode = PictureBoxSizeMode.Zoom;

Upvotes: 2

Related Questions