Create greyscale BMP from RGB BMP

偶尔善良 提交于 2020-01-15 16:42:50

问题


I have 24-bit image, I read bitmap and transform it to the grayscale and save like 8-bit.

RGBTRIPLE temp;
unsigned char t;
...
t = (temp.rgbtBlue * 0.114 + temp.rgbtGreen * 0.587 + temp.rgbtRed * 0.299);
fwrite(&t, sizeof(UCHAR), 1, newFile);

After that image didn't open, I understand I must smth to change in headers. I try change size of file and size of bitmap in headers, but it didn't working.

BITMAPFILEHEADER bfh;
BITMAPINFOHEADER bih;
...
bfh.bfSize = sizeof(UCHAR) * img.Width * img.Height + bfh.bfOffBits;
bih.biSizeImage = sizeof(UCHAR) * img.Width * img.Height;
bih.biCompression = BI_BITFIELDS;
bih.biBitCount = 8;

What I need to change for save image like 8-bit BMP?


回答1:


Actually, the easiest way is not to change anything in the headers. You read 3 values (RGB), convert them to gray using the standard PAL/NTSC formula, and then you can output the calculated gray value 3 times back. That way, you get 1 pixel again, but with the altered value.

Your simply changing just the header doesn't work because for an 8-bit, color indexed image, you also need to provide a color index map -- the palette. In addition, depending on the original image size, you may need to change the stride of each row (that's what it is called -- Google is your friend too!).

As Mark Setchell remarks, BI_BITFIELDS is not what you need here (Wikipedia on BMP). Use BI_RGB for a true color or color indexed image; the other values are very specialized -- and I've never seen them "in the wild".




回答2:


It will be much easier if using Gdiplus class Bitmap's member function ConvertFormat

void GrayScale(Bitmap* bmp)
{
    void* p = malloc(sizeof(Gdiplus::ColorPalette) + 255 * sizeof(ARGB));
    Gdiplus::ColorPalette *cpal = (Gdiplus::ColorPalette*)p;
    for (int i = 0; i < 256; i++) cpal->Entries[i] = Color::MakeARGB(0, i, i, i);
    cpal->Flags = PaletteFlagsGrayScale;
    cpal->Count = 256;
    bmp->ConvertFormat(PixelFormat8bppIndexed, DitherTypeSolid, PaletteTypeCustom, cpal, 0);
    free(p);
}


来源:https://stackoverflow.com/questions/20480726/create-greyscale-bmp-from-rgb-bmp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!