GDI+ 调整像素缩放大小

标签 gdi+ resize pixel

我想使用 GDI 库调整图像大小,这样当我将其大小调整为比以前更大时,就不会发生混合。 (就像在绘画程序中放大图像一样)

EG:如果我的图像宽 2 像素,高 2 像素
(白色,白色,
白色、黑色)
,然后我将其大小调整为 100% 大,高度为 4 像素 x 4 像素
(白,白,白,白,
白色,白色,白色,白色,
白色,白色,黑色,黑色,
白色,白色,黑色,黑色)

我可以使用图形对象的什么 InterpolationMode 或 Smoothing 模式(或其他属性)来实现此目的?到目前为止我尝试过的组合都会导致测试图像中出现灰色。

这是我正在使用的代码

    /// <summary>
    /// Do the resize using GDI+
    /// Credit to the original author
    /// http://www.bryanrobson.net/dnn/Code/Imageresizing/tabid/69/Default.aspx
    /// </summary>
    /// <param name="srcBitmap">The source bitmap to be resized</param>
    /// <param name="width">The target width</param>
    /// <param name="height">The target height</param>
    /// <param name="isHighQuality">Shoule the resize be done at high quality?</param>
    /// <returns>The resized Bitmap</returns>

    public static Bitmap Resize(Bitmap srcBitmap, int width, int height, bool isHighQuality)
    {
        // Create the destination Bitmap, and set its resolution
        Bitmap destBitmap = new Bitmap((int)Convert.ToInt32(width), (int)Convert.ToInt32(height), PixelFormat.Format24bppRgb);
        destBitmap.SetResolution(srcBitmap.HorizontalResolution, srcBitmap.VerticalResolution);

        // Create a Graphics object from the destination Bitmap, and set the quality
        Graphics grPhoto = Graphics.FromImage(destBitmap);
        if (isHighQuality)
        {
            grPhoto.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic;
        }
        else
        {
            grPhoto.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.None; //? this doesn't work
            grPhoto.InterpolationMode = InterpolationMode.NearestNeighbor; //? this doesn't work


        }
        // Do the resize
        grPhoto.DrawImage(srcBitmap,
              new Rectangle(0, 0, width, height),
              new Rectangle(0, 0, srcBitmap.Width, srcBitmap.Height),
              GraphicsUnit.Pixel);

        grPhoto.Dispose();
        return destBitmap;
    }

最佳答案

通过使用 InterpolationMode.NearestNeighbor,您的方向是正确的。但是,使用默认的 PixelOffsetMode,GDI+ 将尝试在像素边缘进行采样,从而导致混合。

要在不混合的情况下进行缩放,您还需要使用 PixelOffsetMode.Half。将您的非高质量案例更改为:

else
{
    grPhoto.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.None;
    grPhoto.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.Half;
}

关于GDI+ 调整像素缩放大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/694095/

相关文章:

c++ - .NET ImageAnimator 是否也可用于 C++?

c# - 从零开始的基本文本框

javascript - 了解 'CSS Tricks' Javascript 模块模式

xcode - 使用 Autolayout 将 XIB 的 Root View 动态调整为其内容的大小

matlab - 在 Matlab 中高效获取像素坐标

c++ - 如何从 Windows 中的 Image 对象获取像素信息?

c# - 重新使用 GDI+ 对象是不好的做法吗? (或 : How to use many nested using blocks without getting headaches? )

c++ - 如何将 GDI+ 的图像* 转换为位图*

Java Odd pack() 行为

Linux在命令行中逐像素创建图像