32位點陣圖與24位點陣圖互相轉換
阿新 • • 發佈:2019-02-02
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跟上文一樣,不贅述。