I am creating a windows form application in which i want to show a image in a picturebox which is selected by user. I made a button on the click of which, browser window appears and user can select picture from his computer but i want that image to fit in the given size of pictureBox. In short, I want to adjust the image size automatically according to my pictureBox but i am unable to do it. Please Help.
here is my code -->>
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog open = new OpenFileDialog();
open.Filter = "Image Files(*.jpg; *.jpeg)|*.jpg; *.jpeg";
if (open.ShowDialog() == DialogResult.OK)
{
pictureBox1.Image = new Bitmap(open.FileName);
sizing(pictureBox1.Image, pictureBox1.Image.Size);
}
}
public void sizing(Image img, Size siz)
{
int sWidth = img.Width;
int sHeight=img.Height;
float nPercent = 0;
float nPercentW = 0;
float nPercentH = 0;
nPercentW = ((float)siz.Width / (float)sWidth);
nPercentH = ((float)siz.Height / (float)sHeight);
if (nPercentH < nPercentW)
nPercent = nPercentH;
else
nPercent = nPercentW;
int destWidth = (int)(sWidth * nPercent);
int destHeight = (int)(sHeight * nPercent);
Bitmap b = new Bitmap(destWidth, destHeight);
pictureBox1.Image = (Image)b;
}

Xavier IkshuPosted May 12, 2015, 4:29 AM
One way to minimize the resize effect is to use an interpolation algorithm. I haven't implemented one myself but I used leadtools sdk which contains two algorithms and I was happy with the results.
If the size difference between the original image and stretched image is not big in your case, you don't need to worry about the image quality dropping down.
André de Mattos FerrazPosted May 4, 2015, 10:25 AM
PictureBox.SizeMode = SizeMode.Stretch