Best Fit Image Resizing
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
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)); }