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>
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>
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!