简体   繁体   中英

How to convert bitmap 16-bit RGBA4444 to 16-bit Grayscale in C++?

I used method:

val = 0.299 * R + 0.587 * G + 0.114 * B;
image.setRGBA(val, val, val, 0);

to convert bitmap (24-bit RGB888 and 32-bit RGBA8888) to grayscale successfully.

Example: BMP 24-bit: 0E 0F EF (BGR) --> 51 51 51 (Grayscale) // using above method

But can't apply for bitmap 16-bit RGBA4444.

Example: BMP 16-bit: 'A7 36' (BGRA) --> 'CE 39' (Grayscale) // ???

Anyone know how?

Are you sure you need RGBA4444 format? Maybe you need an old format where green channel gets 6 bits while red and blue get 5 bits (total 16 bits)

In case of 5-6-5 format - the answer is simple. Just do R = (R>>3); G = (G>>2); B = (B>>3); to reduce the 24 bits into 16. Now just combine them using | operation.

Here is a sample code in C

// Combine RGB into 16bits 565 representation. Assuming all inputs are in range of 0..255
static INT16  make565(int red, int green, int blue){
    return (INT16)( ((red   << 8) & 0xf800)|
                    ((green << 2) & 0x03e0)|
                    ((blue  >> 3) & 0x001f));
}

The method above uses roughly the same structure as the regular ARGB construction method but squeezes the colors to 16 bits instead of 32 like in the following example:

// Combine RGB into 32bit ARGB representation. Assuming all inputs are in range of 0..255
static INT32  makeARGB(int red, int green, int blue){
    return (INT32)((red)|(green << 8)|(blue<<16)|(0xFF000000)); // Alpha is always FF
}

If you do need RGBA4444 then the method would be a combination of the two above

// Combine RGBA into 32bit 4444 representation. Assuming all inputs are in range of 0..255
static INT16  make4444(int red, int green, int blue, int alpha){
    return (INT32)((red>>4)|(green&0xF0)|((blue&0xF0)<<4)|((alpha&0xF0)<<8));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM