Sunday, January 2, 2011

Changing the Opacity of gtk.Pixbuf

Photobomb has lacked the ability to set the opacity of images the way it could set the opacity of text and scribbles. This was because goocanvas.Image lacked this capability, and I could not figure out how to make a pixbuf transparent. I looked through all the pygtk docs, all the PIL docs, and all the cairo docs. I tried a bunch of things, and just couldn't make it happen.

I finally ended up with a solution that works (but is a tad slow on larger images). To start, you need a transparent PNG file loaded into a pixbuf. I do this by storing a transparent PNG image on disk. If I was slicker, I could probably create one out of thin air using the various pixbuf functionalities. You also need a pixbuf that you want to make transparent.

Anyway, given a transparent pixbuf, this function will set the transparency.

    def change_opacity(self, opacity):
change_opacity - changes the opacity of pixbuf by combining
the pixbuf with a pixbuf derived from a transparent .png

opacity - the degree of desired opacity (between 0 and 255)

returns: a pixbuf with the transperancy


trans = self.transparent_img
width = self.pixbuf.get_width()
height = self.pixbuf.get_height()
trans = trans.scale_simple(width,height,gtk.gdk.INTERP_NEAREST)
self.pixbuf.composite(trans, 0, 0, width, height, 0, 0, 1, 1, gtk.gdk.INTERP_NEAREST, opacity)
return trans

I'm sharing it here in case someone else runs into this and can either use my solution, or offer a better one.


  1. I have no words for this great post such a awe-some information i got gathered. Thanks to Author.
    html5 audio player

  2. Opacity Meter. Davinor TOM11 is a modern opacity and transmission meter optimized for thin materials like plastic films, sheets and papers rhopoint iq.