Convert an RGB color image into an 8-digit index color.
First define a macro
// Greyscale conversion#define GREY(r, g, b) (BYTE)(((WORD)r * 77 + (WORD)g * 150 + (WORD)b * 29) >> 8//#define GREY(r, g, b) (BYTE)(((WORD)r * 169 + (WORD)g * 256 + (WORD)b * 87) >> 9)
// Grayscale, Convert RGB to 8 bitvoid gdiplusimage: ipfuncgrayscale () {bitmap * IMA = This-> m_pbitmap; If (! IMA) {return;} // build new 8bpp greyscale bitmapint width = ima-> getwidth (); int Height = ima-> getheight (); rect (0, 0, width, height); bitmapdata bitmapdata_org, bitmapdata_new; bitmap * pgrayimg = new Bitmap (width, height, pixelformat8bppindexed); colorpalette * pal = (colorpalette *) malloc (sizeof (colorpalette) + 256 * sizeof (argb); pal-> COUNT = 256; pal-> flags = 2; for (INT I = 0; I <256; I ++) {Pal-> entries [I] = color: makeargb (255, I);} pgrayimg-> setpalette (PAL); pgrayimg-> lockbits (& rect, imagelockmodewrite, pixelformat8bppindexed, & bitmapdata_new); // lock the bitmap and perform read/write operations on it. The related information is saved to bitmapdata. Status isucess = ima-> lockbits (& rect, imagelockmoderead | imagelockmodewrite, IMA-> getpixelformat (), & bitmapdata_org); byte * _ pixels = (byte *) bitmapdata_org.scan0; // The starting pointer of the memory position in the source rect area, byte * _ newpixles = (byte *) bitmapdata_new.scan0; // The starting pointer of the target bitmap rect area is byte _ gray; // build pixlesswitch (IMA-> getpixelformat () // The pixel format is different and the grayscale processing method is also different {Case pixelformat24bpprgb: {int _ strideoff24 = bitmapdata_org.stride-3 * width; int _ strideoff8 = bitmapdata_new.stride-width; // grayscale for (INT I = 0; I