Resize Image and keep aspect ratio

dannyres

Well-known member
Joined
Aug 29, 2003
Messages
67
Hi guys... just wondering.. how can i resize an image but keep its original ratio or scale... eg say i have a 20*30 image, and i want to resize it to fit in a 60*60 picture box, it would appear as 40*60 and just have a transparent bit on the side.


Dan
 
Its not easy to do it any other way than this:
C#:
public static Size ProportionalSize(Size imageSize, Size MaxW_MaxH)
			{
				double multBy= 1.01;
				double w= imageSize.Width;   double h= imageSize.Height;

				while(w < MaxW_MaxH.Width && h < MaxW_MaxH.Height)
				{
					w= imageSize.Width*multBy;
					h= imageSize.Height*multBy;
					multBy= multBy+.001;
				}

				while(w > MaxW_MaxH.Width || h > MaxW_MaxH.Height)
				{
					multBy= multBy-.001;
					w= imageSize.Width*multBy;
					h= imageSize.Height*multBy;
				}

				if(imageSize.Width < 1)
					imageSize=new Size(imageSize.Width+-imageSize.Width+1, imageSize.Height-imageSize.Width-1);
				if(imageSize.Height < 1)
					imageSize=new Size(imageSize.Width-imageSize.Height-1, imageSize.Height+-imageSize.Height+1);

				imageSize= new Size(Convert.ToInt32(w), Convert.ToInt32(h));
				return imageSize;
			}
I am sure there is some mathmatical way to just multiply one time but as it is I just use a very small number and continue multiplying both side with it until one reaches the max.
 
Just find the smaller of the scale factors (Desired size / current size) for X and Y and use that as the final scaling factor.

<code snippet>

XScale = THUMB_WIDTH / SourceImage.Width
YScale = THUMB_HEIGHT / SourceImage.Height


If XScale < YScale Then
Scale = XScale
Else
Scale = YScale
End If

</code snippet>
 
Back
Top