Home >Backend Development >C++ >How to Convert an Image to 16-bit Grayscale in C#?

How to Convert an Image to 16-bit Grayscale in C#?

DDD
DDDOriginal
2025-01-17 12:47:11558browse

How to Convert an Image to 16-bit Grayscale in C#?

Convert image to 16-bit grayscale in C#

Converting an image to 16-bit-per-pixel grayscale is different than simply setting the individual R, G, and B components to luminance values. Here's how you can achieve this in C#:

<code class="language-csharp">Bitmap grayScaleBP = new System.Drawing.Bitmap(2, 2, System.Drawing.Imaging.PixelFormat.Format16bppGrayScale);</code>

Convert to grayscale

To convert an existing image to grayscale:

<code class="language-csharp">Bitmap c = new Bitmap("fromFile");
Bitmap d;
for (int x = 0; x < ...</code>

(Part of the code is omitted here because the original code is incomplete and has errors)

Faster options

For faster grayscale conversion, you can use ColorMatrix:

<code class="language-csharp">public static Bitmap MakeGrayscale3(Bitmap original)
{
    // 创建新的灰度图像
    Bitmap newBitmap = new Bitmap(original.Width, original.Height);

    // 从新图像获取图形上下文
    using (Graphics g = Graphics.FromImage(newBitmap))
    {
        // 定义灰度颜色矩阵
        ColorMatrix colorMatrix = new ColorMatrix(
            new float[][]
            {
                new float[] {.3f, .3f, .3f, 0, 0},
                new float[] {.59f, .59f, .59f, 0, 0},
                new float[] {.11f, .11f, .11f, 0, 0},
                new float[] {0, 0, 0, 1, 0},
                new float[] {0, 0, 0, 0, 1}
            });

        // 使用灰度颜色矩阵将原始图像绘制到新图像上
        using (ImageAttributes attributes = new ImageAttributes())
        {
            attributes.SetColorMatrix(colorMatrix);
            g.DrawImage(original, new Rectangle(0, 0, original.Width, original.Height),
                        0, 0, original.Width, original.Height, GraphicsUnit.Pixel, attributes);
        }
    }

    return newBitmap;
}</code>

The above is the detailed content of How to Convert an Image to 16-bit Grayscale 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