[cairo] using ARGB32 surfaces with pygame

Bill Spitzak spitzak at thefoundry.co.uk
Mon Feb 23 11:41:44 PST 2009

Cairo is creating the image in ARGB32 format. This defines the order of 
the colors inside a *word*, ie which bits mean each color when 32 bits 
from memory are loaded into a 32-big register in the cpu.

On a little-endian machine the bytes are in BGRA order.

On a big-endian machine the bytes are in ARGB order.

To convert to RGBA depends on the endianess. On a little-endian machine 
you swap byts 0 and 2. On a big-endian machine you rotate 0<-1, 1<-2, 
2<-3, and 3<-0.

Jayesh Salvi wrote:
> Thanks Bill.
> So if I get you correctly, what's happening is cairo is creating color 
> info in ARGB format. pygame is interpreting it as BGRA, because of the 
> byte-order difference. The code I am using is swapping 0th and 2nd 
> color, i.e. B and R - thus leading to RGBA. That's the format I am 
> feeding to pygame.image.frombuffer.
> It sounds like it is inevitable to do this operation when using cairo 
> with pygame. I will see how big performance impact it can cause, if at all.
> For anyone interested, I at least managed to do the swapping without the 
> help of numpy. thanks to: 
> http://www.mail-archive.com/pygame-users@seul.org/msg01707.html
>     def ARGBtoRGBA(self,str_buf):
>         # cairo's ARGB is interpreted by pygame as BGRA due to
>         # then endian-format difference this routine swaps B and R
>         # (0th and 2nd) byte converting it to RGBA format.
>         byte_buf = array.array("B", str_buf)
>         num_quads = len(byte_buf)/4
>         for i in xrange(num_quads):
>             tmp = byte_buf[i*4 + 0]
>             byte_buf[i*4 + 0] = byte_buf[i*4 + 2]
>             byte_buf[i*4 + 2] = tmp
>         return byte_buf.tostring()

Bill Spitzak, Senior Software Engineer
The Foundry, 618 Hampton Drive, Venice, CA, 90291, USA
Tel: +1 310 399-4555 * Fax: +1 310 450-4516 * Web: www.thefoundry.co.uk
The Foundry Visionmongers Ltd * Registered in England and Wales No: 4642027

More information about the cairo mailing list