Transparency in PNGs with reportlab 2.3

Question:

I have two PNGs that I am trying to combine into a PDF using ReportLab 2.3 on Python 2.5. When I use canvas.drawImage(ImageReader) to write either PNG onto the canvas and save, the transparency comes out black. If I use PIL (1.1.6) to generate a new Image, then paste() either PNG onto the PIL Image, it composits just fine. I’ve double checked in Gimp and both images have working alpha channels and are being saved correctly. I’m not receiving an error and there doesn’t seem to be anything my google-fu can turn up.

Has anybody out there composited a transparent PNG onto a ReportLab canvas, with the transparency working properly? Thanks!

Asked By: Dire Fungasaur

||

Answers:

ReportLab uses PIL for managing images. Currently, PIL trunk has patch applied to support transparent PNGs, but you will have to wait for a 1.1.6 release if you need stable package.

Answered By: iElectric

Passing the mask parameter with a value of ‘auto’ to drawImage fixes this for me.

drawImage(......., mask='auto')

More information on the drawImage-function

Answered By: tsidwick

I’ve found that mask='auto' has stopped working for me with reportlab 3.1.8. In the docs it says to pass the values that you want masked out. So what works for me now is mask=[0, 2, 0, 2, 0, 2, ]. Basically it looks like this `mask=[red_start, red_end, green_start, green_end, blue_start, blue_end, ]

The mask parameter lets you create transparent images. It takes 6
numbers and defines the range of RGB values which will be masked out
or treated as transparent. For example with [0,2,40,42,136,139], it
will mask out any pixels with a Red value from 0 or 1, Green from 40
or 41 and Blue of 136, 137 or 138 (on a scale of 0-255). It’s
currently your job to know which color is the ‘transparent’ or
background one.

UPDATE: That masks out anything that is rgb(0, 0, 0) or rgb(1, 1, 1) which obviously might not be the right solution. My problem was people uploading png images with a gray color space. So I need to still figure out a way to detect the color space of the image. and only apply that mask on gray space images.

Answered By: teewuane