Setting individual pixels in .NET Format16bppGrayScale

I am trying to display a small bitmap in memory with .NET, which should be a 16-bit shade of gray. The bitmap format is set to PixelFormat.Format16bppGrayScale. However, Bitmap.SetPixel accepts the Color parameter. The color, in turn, takes one byte for each of R, B, and G (and, optionally, A).

How do I specify a 16-bit gray scale value rather than an 8-bit value when drawing on my bitmap?

+7
bitmap graphics grayscale
source share
1 answer

Regardless of the image format, SetPixel() severely slowed down. I never use it in practice.

You can set pixels much faster using the LockBits method, which allows you to quickly march managed data into unmanaged bitmaps.

Here is an example of how this might look:

 Bitmap bitmap = // ... // Lock the unmanaged bits for efficient writing. var data = bitmap.LockBits( new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadWrite, bitmap.PixelFormat); // Bulk copy pixel data from a byte array: Marshal.Copy(byteArray, 0, data.Scan0, byteArray.Length); // Or, for one pixel at a time: Marshal.WriteInt16(data.Scan0, offsetInBytes, shortValue); // When finished, unlock the unmanaged bits bitmap.UnlockBits(data); 

Note that the 16-bit gray scale is not supported by GDI +, which means that .NET does not help with saving 16bpp grayscale raster images to a file or stream. See http://social.msdn.microsoft.com/forums/en-US/csharpgeneral/thread/10252c05-c4b6-49dc-b2a3-4c1396e2c3ab

+8
source share

All Articles