The accepted version doesn't work correctly if:
- Your image has colors
- Your image is not opaque
- Your image is in a mode different from RGB(A)
In cairo image colors have their value premultiplied by the value of alpha, and they are stored as a 32 bit word using the native CPU endianness. That means that the PIL image:
r1 g1 b1 a1 r2 g2 b2 a2 ...
is stored in cairo in a little endian CPU as:
b1*a1 g1*a1 r1*a1 a1 b2*a2 g2*a2 r2*a2 a2 ...
and in a big endian CPU as:
a1 r1*a1 b1*a1 g1*a1 a2 r2*a2 g2*a2 b2*a2 ...
Here is a version that works correctly on a little endian machine without the NumPy dependency:
def pil2cairo(im):
"""Transform a PIL Image into a Cairo ImageSurface."""
assert sys.byteorder == 'little', 'We don\'t support big endian'
if im.mode != 'RGBA':
im = im.convert('RGBA')
s = im.tostring('raw', 'BGRA')
a = array.array('B', s)
dest = cairo.ImageSurface(cairo.FORMAT_ARGB32, im.size[0], im.size[1])
ctx = cairo.Context(dest)
non_premult_src_wo_alpha = cairo.ImageSurface.create_for_data(
a, cairo.FORMAT_RGB24, im.size[0], im.size[1])
non_premult_src_alpha = cairo.ImageSurface.create_for_data(
a, cairo.FORMAT_ARGB32, im.size[0], im.size[1])
ctx.set_source_surface(non_premult_src_wo_alpha)
ctx.mask_surface(non_premult_src_alpha)
return dest
Here I do the premultiplication with cairo. I also tried doing the premultiplication with NumPy but the result was slower. This function takes, in my computer (Mac OS X, 2.13GHz Intel Core 2 Duo) ~1s to convert an image of 6000x6000 pixels, and 5ms to convert an image of 500x500 pixels.