C# – Fit Image to PictureBox if PictureBox is smaller than Picture

cimagepictureboxwinforms

I have a PictureBox that can have multiple different sizes (depends on screen resolution, window state, etc.). What I would like is to fit my image to the PictureBox when either of the image dimensions (width or height) goes below the respective dimension of the PictureBox.

Example: If the width of the image is greater than that of the PictureBox, but the height of the image is less than that of the PictureBox, it will resize the image width until it equals that of the PictureBox, maintaining the original aspect ratio, and center the image vertically.

If the PictureBox is larger than both image dimensions, then the image is simply centered. That part I have done with PictureBoxSizeMode.AutoSize and some code to center the image based on the sizes of the image and PictureBox.

picbx.ImageLocation = "Image path here";
picbx.SizeMode = PictureBoxSizeMode.AutoSize;
picbx.Anchor = AnchorStyles.None;
picbx.Location = new Point((picbx.Parent.ClientSize.Width / 2) - (picImage.Width / 2),
                           (picbx.Parent.ClientSize.Height / 2) - (picImage.Height / 2));
picbx.Refresh();

One thing I do not need to account for is resizing in the moment. The window does not allow for resizing and there's no need to account for any other situation other than initial load.

I have found many posts that seem to hit close but nothing that fully works. Stretch skews the image, AutoSize does not resize based on container size, and Zoom may work fine for when the image is larger than the PictureBox but I've yet to discover a way to prevent zoom from increasing the image size to fit the PictureBox.

Because I'm setting it to an picbx.ImageLocation and not setting the picbx.Image property, I've yet to figure out a way to resize the image inside of the PictureBox based on the dimension (width or height) that needs to be the reference for resizing.

Best Answer

If you know the PictureBox and Image sizes, you can simply set the appropriate SizeMode - Zoom when width or height of the image is bigger than the picture box, CenterImage otherwise:

var imageSize = picbx.Image.Size;
var fitSize = picbx.ClientSize;
picbx.SizeMode = imageSize.Width > fitSize.Width || imageSize.Height > fitSize.Height ?
    PictureBoxSizeMode.Zoom : PictureBoxSizeMode.CenterImage;