Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert 8 bit color bmp image to 8 bit grayscale bmp

Tags:

c#

bitmap

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 ?

like image 319
crowso Avatar asked Dec 16 '22 06:12

crowso


2 Answers

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.

like image 74
Hans Passant Avatar answered Dec 18 '22 20:12

Hans Passant


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);
like image 29
Emmanuel N Avatar answered Dec 18 '22 18:12

Emmanuel N