Resizing Images Proportionally: Maintaining Maximum Width and Height
In scenarios where images exhibit dimensions surpassing specified maximum limits, it becomes crucial to scale them down proportionally. However, this adjustment requires ensuring that both width and height remain within these constraints. Additionally, the process should adhere to the original aspect ratio.
To accomplish this, a tailored solution is presented:
public static void Test() { using (var image = Image.FromFile(@"c:\logo.png")) using (var newImage = ScaleImage(image, 300, 400)) { newImage.Save(@"c:\test.png", ImageFormat.Png); } } public static Image ScaleImage(Image image, int maxWidth, int maxHeight) { var ratioX = (double)maxWidth / image.Width; var ratioY = (double)maxHeight / image.Height; var ratio = Math.Min(ratioX, ratioY); var newWidth = (int)(image.Width * ratio); var newHeight = (int)(image.Height * ratio); var newImage = new Bitmap(newWidth, newHeight); using (var graphics = Graphics.FromImage(newImage)) graphics.DrawImage(image, 0, 0, newWidth, newHeight); return newImage; }
The ScaleImage method meticulously calculates the appropriate scaling factor to proportionately reduce the image without compromising its aspect ratio. It accomplishes this by comparing the provided maximum width and height with the original image dimensions. Once the correct ratio is determined, it is applied to both dimensions to derive the scaled values. A new bitmap is then created with the scaled dimensions, and the original image is drawn onto it proportionally using the graphics context. The resulting image maintains the maximum constraints while preserving its original proportions.
The above is the detailed content of How to Proportionally Resize Images While Maintaining Maximum Width and Height?. For more information, please follow other related articles on the PHP Chinese website!