Search code examples
pygamecairopycairorsvg

wrong color channels, pygame cairo rsvg drawing


I have cairo+rsvg rendering a .svg file in pygame. But the color channels are wrong.

testing with lion.svg

But image is: enter image description here

I believe I have my RGBA channel order swapped, (He's pink, not yellow). but am not clear on how it works. Here's my code, (which otherwise is rendering right.)

Maybe pygame.display.set_mode(...) or pygame.image.frombuffer(...) is the relevant problem?

import pygame
from pygame.locals import * 
import os
import cairo
import rsvg
import array

WIDTH, HEIGHT = 60,60

class Lion(object):
    """load+draw lion.svg"""
    def __init__(self, file=None):
        """create surface"""
        #  Sprite.__init__(self)
        self.screen = pygame.display.get_surface()                                    
        self.image = None
        self.filename = 'lion.svg'
        self.width, self.height = WIDTH, HEIGHT

    def draw_svg(self):
        """draw .svg to pygame Surface"""
        svg = rsvg.Handle(file= os.path.join('data', self.filename))        
        dim = svg.get_dimension_data()
        self.width , self.height = dim[0], dim[1]

        data = array.array('c', chr(0) * self.width * self.height * 4 )
        cairo_surf= cairo.ImageSurface.create_for_data( data,
            cairo.FORMAT_ARGB32, self.width, self.height, self.width * 4 )
        ctx = cairo.Context(cairo_surf)

        svg.render_cairo(ctx)
        self.image = pygame.image.frombuffer(data.tostring(), (self.width,self.height), "ARGB")

    def draw(self):
        """draw to screen"""
        if self.image is None: self.draw_svg()
        self.screen.blit(self.image, Rect(200,200,0,0))

class GameMain(object):
    """game Main entry point. handles intialization of game and graphics, as well as game loop"""    
    done = False
    color_bg = Color('black') # or also: Color(50,50,50) , or: Color('#fefefe')

    def __init__(self, width=800, height=600):
        pygame.init()

        self.width, self.height = width, height
        self.screen = pygame.display.set_mode(( self.width, self.height ))
        #  self.screen = pygame.display.set_mode(( self.width, self.height ),0,32) # 32bpp for format 0x00rrggbb

        # fps clock, limits max fps
        self.clock = pygame.time.Clock()
        self.limit_fps = True
        self.fps_max = 40

        self.lion = Lion()

    def main_loop(self):
        while not self.done:
            # get input            
            self.handle_events()
            self.draw()
            # cap FPS if: limit_fps == True
            if self.limit_fps: self.clock.tick( self.fps_max )
            else: self.clock.tick()

    def draw(self):
        """draw screen"""
        self.screen.fill( self.color_bg )
        self.lion.draw()
        pygame.display.flip()

    def handle_events(self):
        """handle events: keyboard, mouse, etc."""
        events = pygame.event.get()

        for event in events:
            if event.type == pygame.QUIT: self.done = True
            # event: keydown
            elif event.type == KEYDOWN:
                if event.key == K_ESCAPE: self.done = True

if __name__ == "__main__":         
    print """Keys:
    ESC    = quit
"""    
    game = GameMain()
    game.main_loop()    

Solution

  • Indeed - the byte order for each channel is different from cairo to pygame. You can either juggle with the array before converting it to a string, to post the data in the correct order for pygame (you'd have to swap the green and blue data for each pixel) - or use an aditional dependency: Python's PIL, to properly handle the different data at native speeds.

    There is an snippet for that in pygame's site:

    def bgra_surf_to_rgba_string(cairo_surface):
        # We use PIL to do this
        img = Image.frombuffer(
            'RGBA', (cairo_surface.get_width(),
                     cairo_surface.get_height()),
            cairo_surface.get_data(), 'raw', 'BGRA', 0, 1)
        return img.tostring('raw', 'RGBA', 0, 1)
    
     ...
     # On little-endian machines (and perhaps big-endian, who knows?),
    # Cairo's ARGB format becomes a BGRA format. PyGame does not accept
    # BGRA, but it does accept RGBA, which is why we have to convert the
    # surface data. You can check what endian-type you have by printing
    # out sys.byteorder
    data_string = bgra_surf_to_rgba_string(cairo_surface)
    
    # Create PyGame surface
    pygame_surface = pygame.image.frombuffer(
        data_string, (width, height), 'RGBA')
    

    Check the whole recipe at: http://www.pygame.org/wiki/CairoPygame

    If you don't want to add an aditional dependence (PIL in this case), Python's native arrays allows slice assignment - with those it is possible to swap the data of your blue and green channels at native speeds - try this swapping (may need some tunning :-) this is what worked for me after loading your image above as a png file, not from a cairo context )

    def draw_svg(self):
        """draw .svg to pygame Surface"""
        svg = rsvg.Handle(file= os.path.join('data', self.filename))        
        dim = svg.get_dimension_data()
        self.width , self.height = dim[0], dim[1]
    
        data = array.array('c', chr(0) * self.width * self.height * 4 )
        cairo_surf= cairo.ImageSurface.create_for_data( data,
            cairo.FORMAT_ARGB32, self.width, self.height, self.width * 4 )
        ctx = cairo.Context(cairo_surf)
    
        blue = data[1::4]
        green = data[3::4]
        data[1::4] = green
        data[3::4] = blue
        svg.render_cairo(ctx)
        self.image = pygame.image.frombuffer(data.tostring(), (self.width,self.height), "ARGB")