Resizing Images Proportionally with MaxHeight and MaxWidth Constraints
Maintaining the aspect ratio while resizing images within specified constraints is a common requirement in various applications. Using System.Drawing.Image, you can resize images proportionally while ensuring they stay within the maximum width and height limits.
Problem:
If an image's width or height exceeds the maximum specified, it needs to be resized proportionally. However, after resizing, it's crucial to ensure that neither the width nor height still exceeds the maximum limit. The image should be resized until it fits within the maximum dimensions while maintaining the original aspect ratio.
Solution:
The provided C# code demonstrates how to achieve this:
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; }
Explanation:
By using this technique, you can resize images while maintaining their aspect ratio, ensuring they fit within the specified maximum dimensions.
The above is the detailed content of How to Proportionally Resize Images with MaxHeight and MaxWidth Constraints in C#?. For more information, please follow other related articles on the PHP Chinese website!