imagetransparencypython-imaging-librarypycairo

How to output transparent PNG with Pycairo?


Here's my code:

import cairo
import os
from PIL import Image

imagesize = (512,128)
surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, *imagesize)

cr = cairo.Context(surface)

cr.select_font_face("Verdana", cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_NORMAL)
cr.set_font_size(24)
cr.set_source_rgb(1, 1, 1)

...

surface.write_to_png("MyImage.png")

As you can see I'm drawing some white text to this PNG, but the background defaults to an opaque black. How do I make the png transparent so that only the white text is showing?


Solution

  • I was able to setup a transparent background using set_source_rgba() and using 0.0 for the alpha value:

    cr.set_source_rgba(0.0, 0.0, 0.0, 0.0) # transparent black
    cr.rectangle(0, 0, 512, 128)
    cr.fill()
    

    I then also had to make sure to write the text with something like this:
    # set writing color to white
    cr.set_source_rgb(1, 1, 1)
    
    # write text
    cr.move_to(100,50)
    cr.show_text("hello")
    
    # commit to surface
    cr.stroke()
    

    Here's the full code that works for me:
    import os
    from PIL import Image
    
    imagesize = (512,128)
    surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, *imagesize)
    
    cr = cairo.Context(surface)
    
    # paint background
    cr.set_source_rgba(0.0, 0.0, 0.0, 0.0) # transparent black
    cr.rectangle(0, 0, 512, 128)
    cr.fill()
    
    # setup font
    cr.select_font_face("Verdana", cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_NORMAL)
    cr.set_font_size(24)
    cr.set_source_rgb(1, 1, 1)
    
    # write with font
    cr.move_to(100,50)
    cr.show_text("hello")
    
    # commit to surface
    cr.stroke()
    
    # save file
    surface.write_to_png("MyImage.png")