1、32位图数据转换成24位位图数据:
unsigned char* RGB32TO24(unsigned char* src, int width, int height)
{
uint8_t* data = NULL;
uint32_t src_row_bytes;
uint32_t dst_row_bytes;
uint32_t off;
int i,j;
uint32_t* ptr;
uint8_t* img;
uint32_t color;
int pad;
src_row_bytes = width << 2;
dst_row_bytes = (width * 3 + 3) & ~3;
pad = dst_row_bytes - width * 3;
data = (uint8_t*)malloc(dst_row_bytes * height);
if (!data)
{
return NULL;
}
off = (height - 1) * dst_row_bytes;
ptr = (uint32_t*)src;
for(i = 0; i < height; i++)
{
img = data + off;
for (j = 0; j < width; j++)
{
color = *ptr++;
*img++ = color & 0x000000FF;
*img++ = (color >> 8) & 0x000000FF;
*img++ = (color >> 16) & 0x000000FF;
}
off -= dst_row_bytes;
}
return data;
}
src_row_bytes为32位位图一行所占的内存空间大小,一个像素占据4个字节的数据,所以不用考虑内存对齐问题;dst_row_bytes为24位位图一行所占据内存空间,一个像素3个字节,所以这里需要考虑内存字节对齐问题,dst_row_bytes需要是容纳width*3的最小的4的倍数。
2、24位位图转换成32位位图:
unsigned char* RGB24TO32(unsigned char* src, int width, int height)
{
uint8_t* data;
int row_bytes;
int i,j;
uint8_t* dst;
uint8_t* ptr;
int src_pad;
uint32_t off;
row_bytes = (width * 3 + 3) & ~3;
data = (uint8_t*)malloc(width * 4 * height);
if(!data)
return NULL;
off = (height - 1)*row_bytes;
dst = data;
for(i = 0; i < height;i++)
{
ptr = src + off;
for(j = 0; j < width; j++)
{
*dst++ = *ptr++;
*dst++ = *ptr++;
*dst++ = *ptr++;
*dst++ = 0;
}
off -= row_bytes;
}
return data;
}
row_bytes跟上文一样,不赘述。