0

I'm loading the image dynamically to a pre-existing PictureBox person_img that has all default values and is not sized correctly. I'm expecting to be able to do the sizing dynamically so that all images are 1/3 of people_popup_tab width.

I've tried many ways, including answers from similar questions. My last attempt was to load the image and set the SizeMode to AutoSize so that it would first get rendered at its full size, then I'd be able to get its width and height this way. Then I would use this width and height to know how to proportionately scale the image down.

But the image still renders all wonky. Some also simply don't show up now.

enter image description here

How can I resize the image to 1/3 of people_popup_tab width without losing aspect ratio?

My current code:

person_img.SizeMode = PictureBoxSizeMode.AutoSize;
person_img.Load(thisFaculty.imagePath);
int oldWidth = person_img.Width; 
int oldHeight = person_img.Height;
int newWidth = people_popup_tab.Width / 3;
int newHeight = oldHeight * (newWidth / oldWidth);
person_img.SizeMode = PictureBoxSizeMode.StretchImage;
person_img.Width = newWidth;
person_img.Height = newHeight;
brienna
  • 1,415
  • 1
  • 18
  • 45

1 Answers1

0

First load the image to Bitmap class, than resize your picture box using the real dimensions of the image. Similar to below code

var bmp = new Bitmap(imageFile);
pictureBox1.Width = bmp.Width / 3;
pictureBox1.Height = bmp.Height / 3;
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
pictureBox1.Image = bmp;
Eser
  • 12,346
  • 1
  • 22
  • 32
  • 1
    I think `pictureBox1.SizeMode = PictureBoxSizeMode.Zoom` would help in keeping the PictureBox the same size while maintaining the bitmap proportions. -- Assigning the bitmap this way: `pictureBox1.Image = bmp;`, GDI+ will lock the file. `pictureBox1.Image = new Bitmap(bmp);` can solve this. – Jimi Apr 30 '18 at 20:40