Home >Backend Development >C++ >How to Achieve High-Quality Image Resizing in C#?
Optimizing Image Resizing in C#
Efficiently resizing images within C# applications demands careful manipulation of image properties. While accessing dimensions via Size
, Width
, and Height
is possible, it's not the most effective approach for quality resizing.
Superior Resizing Techniques
For high-fidelity image scaling, the following C# function provides a robust solution:
<code class="language-csharp">public static Bitmap ResizeImage(Image image, int width, int height) { var destRect = new Rectangle(0, 0, width, height); var destImage = new Bitmap(width, height); destImage.SetResolution(image.HorizontalResolution, image.VerticalResolution); using (var graphics = Graphics.FromImage(destImage)) { graphics.CompositingMode = CompositingMode.SourceCopy; graphics.CompositingQuality = CompositingQuality.HighQuality; graphics.InterpolationMode = InterpolationMode.HighQualityBicubic; graphics.SmoothingMode = SmoothingMode.HighQuality; graphics.PixelOffsetMode = PixelOffsetMode.HighQuality; using (var wrapMode = new ImageAttributes()) { wrapMode.SetWrapMode(WrapMode.TileFlipXY); graphics.DrawImage(image, destRect, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, wrapMode); } } return destImage; }</code>
Critical Factors for Quality Resizing
WrapMode.TileFlipXY
: Eliminates edge artifacts ("ghosting") by mirroring the image.SetResolution
: Maintains the original DPI, ensuring consistent image sharpness regardless of size changes.InterpolationMode.HighQualityBicubic
: Employs a high-quality algorithm for smoother scaling transitions.Conclusion
This refined approach guarantees high-quality image resizing in C#. Aspect ratio preservation can be added as a separate feature if required.
The above is the detailed content of How to Achieve High-Quality Image Resizing in C#?. For more information, please follow other related articles on the PHP Chinese website!