Reputation: 1003
I'm trying to resize the image after upload but it doesn't work
What's wrong?
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog open = new OpenFileDialog();
open.Filter = "Image Files(*.jpg; *.jpeg; *.gif; *.bmp)|*.jpg; *.jpeg; *.gif; *.bmp";
if (open.ShowDialog() == DialogResult.OK)
{
var imagem = new Bitmap(open.FileName);
var resizedImage = new Bitmap(imagem, pictureBox1.Size);
pictureBox1.Image = resizedImage;
}
}
Upvotes: 0
Views: 807
Reputation: 20330
Well you don't need this code, just set the SizeMode Property to StretchImage. However the extremely irritating reason your code doesn't work, is changing from one image to another does not in and of itself trigger the picture box to redraw.
The two usual solutions are to either
Call pictureBox1.Invalidate()
after you assign the image, or do pictureBox1.Image = null
, before you assign it.
You might have to do one of these even with SizeMode set, if the image is the same size as the PictureBox, can't remember.
Upvotes: 1
Reputation: 48435
PictureBox already has the ability to resize an image.
If you are assigning the image using the Image
property then you can set the SizeMode property to StretchImage. Which means you code would look like this:
var imagem = new Bitmap(open.FileName);
pictureBox1.Image = imagem;
If you want to assign the image using the BackgroundImage
property then you can set the BackgroundImageLayout property to Stretch. Which means you code would look like this:
var imagem = new Bitmap(open.FileName);
pictureBox1.BackgroundImage = imagem;
From personal experience I have found the PictureBox control to be a pain. If you are needing to change or remove the image at any point I always found I needed to explicitly dispose of the image or it gave me memory leaks, and in some cases just plain errors. It is worth noting that when you need to do custom drawing or rendering in WinForms then the Panel
control is a much better option. You can draw images onto a Panel
too, but depending on your needs, you may be find just using the PictureBox
Upvotes: 3
Reputation: 127603
You need to set the SizeMode of your picture box
from the MSDN
By default, in Normal mode, the Image is positioned in the upper-left corner of the PictureBox, and any part of the image that is too big for the PictureBox is clipped. Using the StretchImage value causes the image to stretch or shrink to fit the PictureBox. Using the Zoom value causes the image to be stretched or shrunk to fit the PictureBox; however, the aspect ratio in the original is maintained.
So change the setting on PictureBox1
from Normal
to StretchImage
or Zoom
depending on which affect you want. It will make it act how you want and you can remove your resize code.
Upvotes: 1