pythontkinterpython-imaging-librarypostscript

How to import a PostScript file into PIL with a transparent background?


Using Pillow 9.5.0, Python 3.11.4, Tk 8.6, and Windows 11 (version 22H2)

On the program i'm working on, I have a tkinter canvas that saves a postscript file, which is then imported into a PIL Image and shown. The problem is that it always has a white background, even when I changed the canvas background color

Here's an excerpt of my example

self.canvas.update()
self.canvas.postscript(file='temp_{insert_garbage_here}.eps')
img = Image.open('temp_{insert_garbage_here}.eps')
img.show()

Is there any way to fix this, so that the background is transparent?

Btw, I tried using

mask = Image.new('L', img.size, color=255)
img.putalpha(mask)

but that didn't change anything

And this is the file the postscript exported: https://www.dropbox.com/scl/fi/fz0xt6is5aicgnqvkcskd/temp_-insert_garbage_here.eps?dl=0&rlkey=yd2pjb61t1rmydm9ky704zcfl


Solution

  • After opening the image, you can call the load() method with transparency=True to tell ghostscript to load the EPS (Encapsulated PostScript) image with a transparent background:

    from PIL import Image
    
    im = Image.open('a.eps')
    im.load(transparency=True)
    
    # Check we now have RGBA inage
    print(im.mode)     # prints "RGBA"
    

    enter image description here