Keywords: C# | Image Processing | System.Drawing | Aspect Ratio | Scaling Padding
Abstract: This article explores techniques for resizing images in C# while maintaining the original aspect ratio and padding with background color to prevent distortion. Based on the System.Drawing library, it details core algorithms for calculating scaling ratios, determining new dimensions, and centering images, with complete code examples and performance considerations.
In image processing applications, it is often necessary to resize images to specific dimensions while preserving the original aspect ratio to avoid distortion. For example, converting a 150×100 pixel image to a 150×150 canvas, padding extra areas with white background. This article details the implementation using the System.Drawing library in C#.
Problem Analysis and Common Pitfalls
Directly using the Graphic.DrawImage method with a target rectangle causes stretching, as it does not automatically maintain aspect ratio. The issue in the original code stems from forcing the image into the target size without considering proportions.
Core Algorithm Implementation
The optimal solution involves these steps:
- Calculate width and height ratios between target canvas and original image:
double ratioX = (double)canvasWidth / originalWidth;anddouble ratioY = (double)canvasHeight / originalHeight; - Select the smaller ratio as the scaling factor to ensure the image fits entirely:
double ratio = ratioX < ratioY ? ratioX : ratioY; - Compute new dimensions after scaling:
int newWidth = Convert.ToInt32(originalWidth * ratio);andint newHeight = Convert.ToInt32(originalHeight * ratio); - Calculate centered position on the canvas:
int posX = (canvasWidth - newWidth) / 2;andint posY = (canvasHeight - newHeight) / 2; - Fill background and draw image:
graphic.Clear(Color.White); graphic.DrawImage(image, posX, posY, newWidth, newHeight);
Code Optimization and Extensions
Referencing other answers, the dimension calculation logic can be encapsulated into a separate method for reusability. For instance, an extension method ResizeKeepAspect accepts maximum width and height parameters, with an option to allow enlargement. Key implementation: decimal rnd = Math.Min(maxWidth / (decimal)src.Width, maxHeight / (decimal)src.Height); returns the new size.
For performance, use InterpolationMode.HighQualityBicubic to ensure quality scaling, and properly manage resources like Graphics and Image objects to prevent memory leaks.
Practical Applications and Considerations
This technique is useful for generating thumbnails or standardizing image sizes. Handle different pixel formats and resolutions carefully, e.g., using bmPhoto.SetResolution to maintain original resolution. For high-concurrency applications, consider asynchronous processing and caching mechanisms to enhance performance.