Home >Backend Development >C++ >How to Resize Images Efficiently in C#?

How to Resize Images Efficiently in C#?

Susan Sarandon
Susan SarandonOriginal
2025-01-31 00:56:08246browse

Method of high -efficiency C#image size

Question:

System.Drawing.image class provides SIZE, Width, and Height Get () properties. But how to adjust the size of the Image object when running in C#?

Solution:

Use the heavy load with size () to create a new image. As shown in the example, a IMAGE object that has been adjusted in size will be generated:

However, the following functions can be used to achieve higher quality adjustment size:
<code class="language-csharp">// objImage 是原始 Image
Bitmap objBitmap = new Bitmap(objImage, new Size(227, 171));</code>

Other details:
<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);

    // 使用 Graphics 类绘制调整大小的图像
    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>

Prevent transparent pixels outside the boundary boundary, which affects the image that is adjusted.

    Holding DPI has nothing to do with the size of the physics, and the quality can be improved when reducing the size of the image or printing.
  • wrapMode.SetWrapMode(WrapMode.TileFlipXY) Various compositing, interpolation, Smoothing, and PixeloffsetMode set control to adjust the rendering quality of large and small images.
  • This function does not keep the processing ratio and leaves it for developers to decide on its own. destImage.SetResolution

The above is the detailed content of How to Resize Images Efficiently 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