问题
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