0

我需要手动将 rgba8 转换为 rgba5551。我从另一篇文章中找到了一些有用的代码,并想对其进行修改以将其从 rgba8 转换为 rgba5551。我真的没有经验,也没有自己弄乱代码的运气。

void* rgba8888_to_rgba4444( void* src, int src_bytes)
{
    // compute the actual number of pixel elements in the buffer.
    int num_pixels = src_bytes / 4;
    unsigned long*  psrc = (unsigned long*)src;
    unsigned short* pdst = (unsigned short*)src;
    // convert every pixel
    for(int i = 0; i < num_pixels; i++){
        // read a source pixel
        unsigned px = psrc[i];
        // unpack the source data as 8 bit values
        unsigned r = (px << 8)  & 0xf000;
        unsigned g = (px >> 4)  & 0x0f00;
        unsigned b = (px >> 16) & 0x00f0;
        unsigned a = (px >> 28) & 0x000f;
        // and store
        pdst[i] = r | g | b | a;
    }
    return pdst;
}
4

1 回答 1

1

RGBA5551 的值是将颜色信息压缩为 16 位 - 或两个字节,只有一位用于 Alpha 通道(打开或关闭)。另一方面,RGBA8888 为每个通道使用一个字节。(如果您不需要 Alpha 通道,我听说 RGB565 更好——因为人类对绿色更敏感)。现在,有了 5 位,你得到了 0 到 31 的数字,所以 r、g 和 b 都需要转换为 0 到 31 之间的某个数字,并且由于它们最初都是一个字节(0-255),所以我们相乘每个 31/255。这是一个将 RGBA 字节作为输入并将 RGBA5551 输出为 short 的函数:

short int RGBA8888_to_RGBA5551(unsigned char r, unsigned char g, unsigned char b, unsigned char a){
    unsigned char r5 = r*31/255; // All arithmetic is integer arithmetic, and so floating points are truncated. If you want to round to the nearest integer, adjust this code accordingly.
    unsigned char g5 = g*31/255;
    unsigned char b5 = b*31/255;
    unsigned char a1 = (a > 0) ? 1 : 0; // 1 if a is positive, 0 else. You must decide what is sensible.

    // Now that we have our 5 bit r, g, and b and our 1 bit a, we need to shift them into place before combining.

    short int rShift = (short int)r5 << 11; // (short int)r5 looks like 00000000000vwxyz - 11 zeroes. I'm not sure if you need (short int), but I've wasted time tracking down bugs where I didn't typecast properly before shifting.
    short int gShift = (short int)g5 << 6;
    short int bShift = (short int)b5 << 1;

    // Combine and return
    return rShift | gShift | bShift | a1;
}

当然,您可以压缩此代码。

于 2013-05-26T07:53:51.870 回答