30

i got a problem with image scaling in C#.

I have a picture Box with given Size : e.g. width = 800px height = 600px

I am loading different images into that picture box, small ones ( 400x400) and big ones (800+ x 600+)

My images are getting resized if they do not fit into box. But they are always resized to MAX width and height of PictureBox. So the aspect ratio is destroyed.

Can anybody help to identify / fix the problem?

Classes:

Form1.cs

ImageHandling.cs (commented out)

ImageUtilities.cs

Examples:

Problem 1: My Version
enter image description here

vs Original Source enter image description here

Problem 2:
My Version
enter image description here

vs Original Source
enter image description here

How i want it:

Solution
enter image description here

Hamed
  • 2,084
  • 6
  • 22
  • 42
pila
  • 928
  • 3
  • 11
  • 28

2 Answers2

61
this.PictureBox1.SizeMode = PictureBoxSizeMode.Zoom;

Set that property to your PictureBox and the size of the image will increased or decreased to fit the PictureBox maintaining the size ratio.

For more info: http://msdn.microsoft.com/en-us/library/system.windows.forms.picturebox.sizemode.aspx

Forte L.
  • 2,772
  • 16
  • 25
  • 1
    It works now Thanks! I removed my resizing method and it worked. BUT my pictures are not in original size if they are smaller than picturebox. Any idea? – pila Sep 28 '12 at 19:45
  • so, what you need is to resize the image only if it's bigger than the picturebox? and keep the size if it's smaller? – Forte L. Sep 28 '12 at 20:01
  • When the picture i want to load is smaller than my picture box, it is "zoomed" like the SizeMode says, but i dont want to zoom it. i want to display it in original size by keeping the aspect ratio. – pila Sep 28 '12 at 20:04
  • 4
    then you'll probably have to do something like: `if(image.Width < pictureBox1.Width && image.Height < pictureBox1.Height){pictureBox1.SizeMode = PictureBoxSizeMode.Normal;}else{pictureBox1.SizeMode = PictureBoxSizeMode.Zoom;}` – Forte L. Sep 28 '12 at 20:08
0

I handled this by resetting the SizeMode on the PictureBox's resize method.

This is, essentially, the same answer as above, but it's formatted much better.

private void ScaleImage()
{
  if (pbInfo.Image == null)
    return;

  if (pbInfo.Image.Width > pbInfo.Width || pbInfo.Image.Height > pbInfo.Height)
    pbInfo.SizeMode = PictureBoxSizeMode.Zoom;
  else
    pbInfo.SizeMode = PictureBoxSizeMode.Normal;
}
LarsTech
  • 80,625
  • 14
  • 153
  • 225