首页 > 解决方案 > 将 R、G、B 数组转换为 RGB 数组

问题描述

我有我的 R、G 和 B 数组,它们是 uint8_t

uint8_t * R, * G, * B, * A;
int stride_r, stride_g, stride_b, stride_a;
getRGB(img, &R, &G, &B, &A, &stride_r, &stride_g, &stride_b, &stride_a);
// All the strides are equal and the img is img_width and img_height dimension
int RBG[stride_r * img_height];

所以我的问题是以下工作:

for(int i=0; i<stride_r * img_height; ++i)
{
    RGB[i] = R[i] << 24 + G[i] << 16 + B[i] << 8 + A[i];
}

标签: c++imagebit-manipulation

解决方案


你在正确的轨道上。但是,您需要使用按位或操作将它们组合起来,而不是四个组成字节添加到四字节整数中:

for(int i = 0; i < stride_r * img_height; ++i)
{
    RGB[i] = (R[i] << 24) | (G[i] << 16) | (B[i] << 8) | A[i];
}

另外,请记住,在许多/大多数平台上,组件实际上以“反向”顺序存储(以十六进制格式,0xaaBBGGRR);因此,如果您的系统这种情况,那么您将需要:

for(int i = 0; i < stride_r * img_height; ++i)
{
    RGB[i] = (A[i] << 24) | (B[i] << 16) | (G[i] << 8) | R[i];
}

此外,正如评论中提到的,您应该使用类型创建RGB一个无符号整数数组,最好是固定的32 位大小uint32_t


推荐阅读