Warning: Parameter 3 to ExtToggleDisplay::toggleDisplay() expected to be a reference, value given in /home/ikewiki/public_html/w/includes/parser/Parser.php on line 3470
Best Fit Image Resizing - IkeWiki

Best Fit Image Resizing

Jump to: navigation, search
Categories » Programming » .NET Programming » ASP.NET » Best Fit Image Resizing
Categories » Programming » Web Programming » ASP.NET » Best Fit Image Resizing
Categories » Programming » Web Programming » PHP » Best Fit Image Resizing

Fitting an image into a box while maintaining original aspect ratio

You have to consider both the aspect ratio of the box and of the original image.

This page has a function to calculate the new dimensions: Resizing an Image in a PictureBox for Best Fit

It turns out the code from the above link is flawed...

My code

This code worked really well:

NOTE: I would be better off using nullable ints on the W and H input vars.

// Set W or H to 0 to ignore that option
public static System.Drawing.Size getScaledImageDimensions(int currentImageWidth, int currentImageHeight, int desiredImageWidth, int desiredImageHeight)
{
	double scaleImageMultiplier = 1;
	if ((desiredImageWidth == 0) && (desiredImageHeight == 0))
		scaleImageMultiplier = 1;
 
	else if (desiredImageHeight == 0)
		scaleImageMultiplier = (double)desiredImageWidth / (double)currentImageWidth;
 
	else if (desiredImageWidth == 0)
		scaleImageMultiplier = (double)desiredImageHeight / (double)currentImageHeight;
 
	else
		scaleImageMultiplier =
		Math.Min((double)desiredImageHeight / (double)currentImageHeight, (double)desiredImageWidth / (double)CurrentImageWidth);
 
	return new System.Drawing.Size(
	(int)(currentImageWidth * scaleImageMultiplier),
	(int)(currentImageHeight * scaleImageMultiplier));
}
Personal tools
Namespaces
Variants
Actions
Navigation
Categories
Toolbox