Tony's ramblings on Open Source Software, Life and Photography

Load Multiple Image Formats Into Cairo Surfaces (Python)

This drove me up the wall trying to figure it out, but loading jpg's or tiff's into a Cairo surface with Python really isn't all that hard.

The trick is to load it into a gtk.gdk.pixbuf first. here's an example:

pixbuf = gtk.gdk.pixbuf_new_from_file(filename)
x = pixbuf.get_width()
y = pixbuf.get_height()
''' create a new cairo surface to place the image on '''
surface = cairo.ImageSurface(0,x,y)
''' create a context to the new surface '''
ct = cairo.Context(surface)
''' create a GDK formatted Cairo context to the new Cairo native context '''
ct2 = gtk.gdk.CairoContext(ct)
''' draw from the pixbuf to the new surface '''
ct2.set_source_pixbuf(pixbuf,0,0)
ct2.paint()
''' surface now contains the image in a Cairo surface '''

Of course you could bypass stamping it onto a Cairo surface entirely and just use the original pixmap for most things, but for doing affine translations I needed an actual surface and not a context to one. Otherwise you have to remember what is accessible through gdk and what is a native Cairo surface.

With a little bit of pipe magic, you can even do image manipulation externally before loading it, and never have to create a temp file:

import subprocess
''' Load the pixbuf from the embedded thumbnail in a RAW file using dcraw '''
p1 = subprocess.Popen(["dcraw","-e","-c",filename],stdout=subprocess.PIPE)
myloader = gtk.gdk.PixbufLoader()
myloader.write(p1.stdout.read())
myloader.close()
pixbuf = myloader.get_pixbuf()

Then pass the newly created pixbuf (actually a JPG created from dcraw) into the first swatch of code, and you've gone from the embedded thumbnail inside a RAW camera image into a Cairo surface.


Categories:

Post new comment

The content of this field is kept private and will not be shown publicly. If you have a Gravatar account associated with the e-mail address you provide, it will be used to display your avatar.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <br> <p>
  • Lines and paragraphs break automatically.

More information about formatting options

CAPTCHA
This question is for preventing automated spam submissions. It is case sensitive.
Image CAPTCHA
Enter the characters shown in the image.