C#: Resize picturebox to fit image

cimagewinforms

In my app (winforms), I'd like to load in different images. These images have different sizes, and different aspect ratios (let's say I have a 400×400, and a 1920×1200.) Now I have a picturebox to put these images in, and the picturebox's SizeMode property is set to Zoom.

Now I have an image in a picturebox, that is resized to fit within the picuterbox's boundaries. But if the picturebox has a different aspect ratio than the image has, I will be left with some unwanted empty space.
Setting the SizeMode to stretch, is not an option.

?: So I'd like to know, if there is a way to get the size of the auto-resized image, so I can change the size of the picturebox accordingly.

Image myImg = new Image.FromFile(..//landscape.jpg)
int getWidth = myImg.Width;
int getHeight = myImg.Height;
// This does not work, as it gets the original size of the image (eg: in case of a 1920x1200, it gets 1920 and 1200 respectively)

This is what happens right now:

Wrong ratio
Wrong ratio

This is what I'd like to have:

Required ratio
Because the app should be able to process any image, I need to set these values dynamically, so no values can be preset.

Best Answer

Let us say the box is 400x400. When a picture goes into the box, it is resized to fit within the boxes boundaries but keeps it's aspect ratio. So what we need to do is calculate the new size of the image within the box, and resize the box to match.

Image myImg = new Image.FromFile(..//landscape.jpg)
int getWidth = myImg.Width;
int getHeight = myImg.Height;
double ratio = 0;
if(getWidth>getHeight)
{
    ratio = getWidth/400;
    getWidth=400;
    getHeight=(int)(getHeight/ratio);
}
else
{
    ratio = getHeight/400;
    getHeight=400;
    getWidth=(int)(getWidth/ratio);
}
pictureBox.Width=getWidth;
pictureBox.Height=getHeight;

(Don't know the exact classes so might throw an error or two, concept is sound though)