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

How to Efficiently Convert Images to 16-bit Grayscale in C#?

Barbara Streisand
Release: 2025-01-17 13:01:10
Original
396 people have browsed it

How to Efficiently Convert Images to 16-bit Grayscale in C#?

Create 16-bit grayscale image in C#

Convert the image to 16-bit grayscale format without adjusting the RGB components one by one, you can directly use the System.Drawing.Imaging.PixelFormat enumeration.

Create grayscale bitmap

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

This will create an empty 16-bit grayscale bitmap.

Convert existing image

To convert an existing color image to grayscale, you can iterate over its pixels and set the color of each pixel to grayscale, extracting the brightness information from the original color. (Code examples for pixel traversal and grayscale conversion are omitted here because the complete code is not provided in the original article, only the code to create the bitmap.)

Optimization plan

To speed up grayscale conversion, you can use the ColorMatrix class to apply a grayscale transformation before drawing the original image:

<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>
Copy after login

This method utilizes ColorMatrix to efficiently convert images to grayscale.

The above is the detailed content of How to Efficiently Convert Images to 16-bit Grayscale in C#?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template