This is my bitmap object
Bitmap b = new Bitmap(columns, rows, PixelFormat.Format8bppIndexed);
BitmapData bmd = b.LockBits(new Rectangle(0, 0, columns, rows), ImageLockMode.ReadWrite, b.PixelFormat);
How do i convert this into a 8 bit grayscale bitmap ?
Yes, no need to change the pixels, just the palette is fine. ColorPalette is a flaky type, this sample code worked well:
var bmp = Image.FromFile("c:/temp/8bpp.bmp");
if (bmp.PixelFormat != System.Drawing.Imaging.PixelFormat.Format8bppIndexed) throw new InvalidOperationException();
var newPalette = bmp.Palette;
for (int index = 0; index < bmp.Palette.Entries.Length; ++index) {
var entry = bmp.Palette.Entries[index];
var gray = (int)(0.30 * entry.R + 0.59 * entry.G + 0.11 * entry.B);
newPalette.Entries[index] = Color.FromArgb(gray, gray, gray);
}
bmp.Palette = newPalette; // Yes, assignment to self is intended
if (pictureBox1.Image != null) pictureBox1.Image.Dispose();
pictureBox1.Image = bmp;
I don't actually recommend you use this code, indexed pixel formats are a pita to deal with. You'll find a fast and more general color-to-grayscale conversion in this answer.
Something like:
Bitmap b = new Bitmap(columns, rows, PixelFormat.Format8bppIndexed);
for (int i = 0; i < columns; i++)
{
for (int x = 0; x < rows; x++)
{
Color oc = b.GetPixel(i, x);
int grayScale = (int)((oc.R * 0.3) + (oc.G * 0.59) + (oc.B * 0.11));
Color nc = Color.FromArgb(oc.A, grayScale, grayScale, grayScale);
b.SetPixel(i, x, nc);
}
}
BitmapData bmd = b.LockBits(new Rectangle(0, 0, columns, rows), ImageLockMode.ReadWrite, b.PixelFormat);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With