Working with Images

Learn how to use images in Pycairo.

Loading an image into Pycairo

Before we look at the SurfacePattern, we will take a quick look at how we can load an image into Pycairo.

Surface provides a create_from_png class method that reads a PNG image from a file, creates a suitable surface, and fills the surface with the image pixels. Here is how it can be used:

Press + to interact
import cairo
import math
image = cairo.ImageSurface.create_from_png('tiger.png')
print("width:", image.get_width())
print("height:", image.get_height())
image.write_to_png('output/image.png')

This code reads in a PNG file called tiger.png, but we can use any PNG image. The newly-created surface, called image, is queried for size and format. The image is ...