Search code examples
c#filebitmapjpegpicturebox

C# - Changing SizeMode of picturebox


    private void button1_Click(object sender, EventArgs e)
    {
        OpenFileDialog open = new OpenFileDialog();
        open.Filter = "Image Files(*.jpg; *.jpeg; *.gif; *.png; *.bmp)|*.jpg; *.jpeg; *.gif; *.png; *.bmp";
        if(open.ShowDialog() == DialogResult.OK)
        {
            tbFileName.Text = open.FileName;
            pictureBox1.Image = new Bitmap(open.FileName);
        }
    }

So I want to make an if statement, if the image is too big for the initial size of the image box (520, 301), set the image box sizemode to autosize, otherwise just put it in there.

I'm pretty sure that you can change it by using this:

picturebox1.SizeMode = PictureBoxSizeMode.AutoSize;

But I don't know how to write the if statement.


Solution

  • Just load your file to Bitmap and then compare its Height and Width property with our custom size (500 x 301). like

    ...
    tbFileName.Text = open.FileName;
    
    using (Bitmap bmp = new Bitmap(open.FileName))
    {
        if (bmp.Height >= 301 && bmp.Width >= 500)
            pictureBox1.SizeMode = PictureBoxSizeMode.AutoSize;
    
        pictureBox1.Image = bmp;
    }