Fast Converting RGBA to ARGB

后端 未结 4 925
半阙折子戏
半阙折子戏 2020-12-18 08:16

I am trying to convert a rgba buffer into argb, is there any way to improve the next algorithm, or any other faster way to perform such operation? Taking into account that t

4条回答
  •  忘掉有多难
    2020-12-18 09:11

    Assuming that the code is not buggy (just inefficient), I can guess that all you want to do is swap every second (even-numbered) byte (and of course invert the buffer), isn't it?

    So you can achieve some optimizations by:

    • Avoiding the shift and masking operations
    • Optimizing the loop, eg economizing in the indices calculations

    I would rewrite the code as follows:

    int y, x;
    
    for (y = 0; y < height; y++)
    {
        unsigned char *pRGBA= (unsigned char *)(rgbaBuffer+y*width);
        unsigned char *pARGB= (unsigned char *)(argbBuffer+(height-y-1)*width);
        for (x = 4*(width-1); x>=0; x-=4)
        {
            pARGB[x  ]   = pRGBA[x+2];
            pARGB[x+1]   = pRGBA[x+1];
            pARGB[x+2]   = pRGBA[x  ];
            pARGB[x+3]   = 0xFF;
        }
    }
    

    Please note that the more complex indices calculation is performed in the outer loop only. There are four acesses to both rgbaBuffer and argbBuffer for each pixel, but I think this is more than offset by avoiding the bitwise operations and the indixes calculations. An alternative would be (like in your code) fetch/store one pixel (int) at a time, and make the processing locally (this econimizes in memory accesses), but unless you have some efficient way to swap the two bytes and set the alpha locally (eg some inline assembly, so that you make sure that everything is performed at registers level), it won't really help.

提交回复
热议问题