简体   繁体   中英

Generate a mask of the alpha channel from a bitmap

I need to generate a grey scale bitmap from the alpha channel of a System.Drawing.Bitmap.

I tried using GetPixel and SetPixel but this does not work with bitmaps with a PixelFormat of Format16bppGrayScale.

For example, setting all the pixels in my greyscale image to black. SetPixel throws an exception.

var bitmap = new Bitmap(16, 16, PixelFormat.Format16bppGrayScale); 
for (int x = 0; x < bitmap.Width; x++)
{
    for (int y = 0; y < bitmap.Height; y++)
    {
       bitmap.SetPixel(x,y, Color.Black);
    }
}

You can use BitmapData bitmapDataIn = bitmap.LockBits(... ) Then use use byte* pDataIn = (byte*)bitmapDataIn.Scan0; to get a pointer to raw bitmap data.

This is 32-bit bitmap data, though

pDataIn[y * iStrideSize + x * 4 + 0] //Blue
pDataIn[y * iStrideSize + x * 4 + 1] //Greed
pDataIn[y * iStrideSize + x * 4 + 2] //Red 
pDataIn[y * iStrideSize + x * 4 + 3] //Alpha

You can modify or read pixel values with the pointer

This is copy-paste of my code,

unsafe
            {
                byte* pDataIn = (byte*)bitmapDataIn.Scan0;
                int iStrideSize = bitmapDataIn.Stride; //one row size in bytes, iWidth * 4
                int y, x;
                byte B, G, R, A;

                for (y = 0; y < iHeight; y++)
                {
                    for (x = 0; x < iWidth; x++)
                    {
                        B = pDataIn[y * iStrideSize + x * 4 + 0];
                        G = pDataIn[y * iStrideSize + x * 4 + 1];
                        R = pDataIn[y * iStrideSize + x * 4 + 2];
                        A = pDataIn[y * iStrideSize + x * 4 + 3];

                    }
                }


                bitmap.UnlockBits(bitmapDataIn);
            }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM