Piyush chhabra

Piyush chhabra

  • NA
  • 83
  • 16.7k

image resizing in pictureBox

May 4 2015 6:22 AM
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;
}
 

Answers (2)