I have made function and enum. For convinience I have created an enum for layer selection, "WhichLayer"
public enum WhichLayer
{
Red=0,
Green=1,
Blue=2
}
Then, the functions as follows:
private Bitmap GetSpecificLayer(Bitmap image, WhichLayer layer)
{
Rectangle rect=new Rectangle(0, 0, image.Width, image.Height);
BitmapData dataIn = image.LockBits(rect, ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
Bitmap result = new Bitmap(rect.Width,rect.Height,PixelFormat.Format8bppIndexed);
result.SetResolution(image.HorizontalResolution, image.VerticalResolution);
SetGrayscalePalette(result);
BitmapData dataOut = result.LockBits(rect, ImageLockMode.WriteOnly, PixelFormat.Format8bppIndexed);
int strideIn = dataIn.Stride;
int strideOut = dataOut.Stride;
int lineOffsetIn = dataIn.Stride - rect.Width * 3;
int lineOffsetOut = dataOut.Stride - rect.Width;
int ind=0;
switch(layer)
{
case WhichLayer.Blue: ind=0; break;
case WhichLayer.Green:ind=1; break;
case WhichLayer.Red: ind = 2;break;
}
unsafe
{
byte* pIn = (byte*)(void*)dataIn.Scan0;
byte* pOut = (byte*)(void*)dataOut.Scan0;
for (int y = 0; y < image.Height; y++)
{
for (int x = 0; x < image.Width; x++)
{
pOut[0] = pIn[ind];
pIn += 3;
pOut++;
}
pIn += lineOffsetIn;
pOut += lineOffsetOut;
}
}
image.UnlockBits(dataIn);
result.UnlockBits(dataOut);
return result;
}
private static void SetGrayscalePalette(Bitmap b)
{
ColorPalette pal = b.Palette;
for (int i = 0; i < 256; i++)
pal.Entries[i] = Color.FromArgb(255, i, i, i);
b.Palette = pal;
}
The above is only for RGB images (24-bit). If you need for all RGB color images you may do separately for each format. Or you may use third party tools. You may find one here:
http://www.artuxsoft.com[
^]