问题
The following code is used to create a 8 bit bitmap
Bitmap b = new Bitmap(columns, rows, PixelFormat.Format8bppIndexed);
BitmapData bmd = b.LockBits(new Rectangle(0, 0, columns, rows), ImageLockMode.ReadWrite, b.PixelFormat);
But when i save it it is saved as a 8 bit color bitmap. Is it possible to directly create a 8 bit grayscale bitmap without creating a 8 bit color bitmap and later having to convert it to a grayscale ?
回答1:
If you have a bitmap that has a palette then there's not really a notion of whether the bmp is greyscale or not. As long as all colours in the palette are greyscale then the bmp is.
This code should help (it's VB but should be easy to translate):
Private Function GetGrayScalePalette() As ColorPalette
Dim bmp As Bitmap = New Bitmap(1, 1, Imaging.PixelFormat.Format8bppIndexed)
Dim monoPalette As ColorPalette = bmp.Palette
Dim entries() As Color = monoPalette.Entries
Dim i As Integer
For i = 0 To 256 - 1 Step i + 1
entries(i) = Color.FromArgb(i, i, i)
Next
Return monoPalette
End Function
Found here: http://social.msdn.microsoft.com/Forums/en-us/vblanguage/thread/500f7827-06cf-4646-a4a1-e075c16bbb38
回答2:
I just met this problem and solved it, under the help of this:enter link description here
But I will put my quick solution here, hope it helps you. :) BITMAP files contain four parts, one is the palette, which decides how the colors should be displayed. So here we modify the palette of our Bitmap file:
myBMP = new Bitmap(_xSize, _ySize, _xSize, System.Drawing.Imaging.PixelFormat.Format8bppIndexed, _pImage);
//_pImage is the pointer for our image
//Change palatte of 8bit indexed BITMAP. Make r(i)=g(i)=b(i)
ColorPalette _palette = myBMP.Palette;
Color[] _entries = _palette.Entries;
for (int i = 0; i < 256; i++)
{
Color b = new Color();
b = Color.FromArgb((byte)i, (byte)i, (byte)i);
_entries[i] = b;
}
myBMP.Palette = _palette;
return myBMP;
来源:https://stackoverflow.com/questions/8603596/how-can-i-define-a-8-bit-grayscale-image-directly