如何将BGRA缓冲区转换为RGBA缓冲区格式?

时间:2012-11-16 19:27:20

标签: c++ video-streaming rgba

如何在C ++中将BGRA缓冲区转换为RGBA缓冲区格式

void ConvertBetweenBGRAandRGBA(unsigned char* input, int pixel_width,int pixel_hight,
                           unsigned char* output) {

        for (int y = 0; y < pixel_hight; y++) {
        for (int x = 0; x < pixel_width; x++) {
        const unsigned char* pixel_in = &input[y * x * 4];

        unsigned char* pixel_out = &output[y * x * 4];
        pixel_out[0] = pixel_in[2];
        pixel_out[1] = pixel_in[1];
        pixel_out[2] = pixel_in[0];
        pixel_out[3] = pixel_in[3];
     }
}

但我没有获得背景颜色。

请任何人帮助我?

2 个答案:

答案 0 :(得分:1)

这不是C#,所以请适当地重新标记。

假设这是位图数据,首先,您需要找出图像的 stride 。步幅是每行像素使用的字节数。这并不总是等于bytes_per_pixel * pixels_per_row。它通常与四个字节对齐,因此在这种情况下(因为ARGB像素每个像素使用四个字节),你应该没问题。

其次,获取像素(x,y)地址的公式是错误的。像素按行主要顺序存储。这意味着,从像素缓冲区中的偏移0开始,您将看到一行完整的像素数据;然后另一个完整的行;等等。每行像素数据都有一个完整的字节跨度。

可以这样做:

const unsigned char* pixel_in = &input[((y * pixel_width) + x) * 4];

但是如果你的步幅确实等于图像宽度,那么每次都不需要计算地址,因为像素将按顺序存储:

void ConvertBetweenBGRAandRGBA(unsigned char* input, int pixel_width,
    int pixel_height, unsigned char* output)
{
    int offset = 0;

    for (int y = 0; y < pixel_height; y++) {
        for (int x = 0; x < pixel_width; x++) {
            output[offset] = input[offset + 2];
            output[offset + 1] = input[offset + 1];
            output[offset + 2] = input[offset];
            output[offset + 3] = input[offset + 3];

            offset += 4;
        }
    }
}

如果仍未显示正确,请确认正确的像素包装是什么。它应该是ARGB或BGRA;我从来没有听说过像RGBA这样的像素。

答案 1 :(得分:0)

Jeff 的 awnser 可以工作,但有一些细节您永远不会存储第一个偏移量。 只需添加一个临时值,它就会像对我一样具有魅力:D

void ConvertBetweenBGRAandRGBA(unsigned char* input, int pixel_width, int pixel_height, unsigned char* output)
{
    int offset = 0;

    for (int y = 0; y < pixel_height; y++) {
        for (int x = 0; x < pixel_width; x++) {

            auto temp = output[offset];
            output[offset] = input[offset + 2];
            output[offset + 1] = input[offset + 1];
            output[offset + 2] = temp;
            output[offset + 3] = input[offset + 3];

            offset += 4;
        }
    }
}
相关问题