Home >Backend Development >C++ >How to Achieve High-Quality Image Resizing in C#?

How to Achieve High-Quality Image Resizing in C#?

Susan Sarandon
Susan SarandonOriginal
2025-01-31 01:11:08400browse

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.
  • Compositing Settings: Precisely control pixel blending and rendering for superior results.
  • InterpolationMode.HighQualityBicubic: Employs a high-quality algorithm for smoother scaling transitions.
  • Smoothing and Pixel Offset: Minimize jagged edges (aliasing) and enhance line clarity.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn