简体   繁体   中英

How to save an .EPS file to PNG with transparency in Python

I'm building a Paint-like app Since I want the freedom to reposition and modify the shape properties later, I am using Tkinter to draw shapes on Canvas instead of PIL Draw or anything else. From other answers, I found how to save a canvas as PNG by 1st creating a postscript file and then converting it to PNG using PIL.

Now the problem is the EPS file has transparent spaces but the PNG file fills those voids with a White background color. I'm not sure where I am going wrong.

Below is the function I used.

def saveImg(event):
    global canvas
    canvas.postscript(file="my_drawing.eps", colormode='color')
    imgNew = Image.open("my_drawing.eps")
    imgNew.convert("RGBA")
    imgNew.thumbnail((2000,2000), Image.ANTIALIAS)
    imgNew.save('testImg.png', quality=90)

Looks like transparency is not supported. From the docs :

The EPS driver can read EPS images in L, LAB, RGB and CMYK mode, but Ghostscript may convert the images to RGB mode rather than leaving them in the original color space.

When you load in RGB (instead of RGB A ) the alpha channel information is discarded and converting it to RGBA later will not recover it.

Your best shot is porting it to more recent toolkits like cairo or QT or converting the file using GhostScript directly as suggested by PM2Ring.

For the GS approach in order to set the width and height of the output file you must use the -rN switch where N is the resolution in PPI (pixels per inch). You must do the math in order to get target resolution from the EPS bounding box and the desired output size.

Or you can render to a fixed resolution first, lets say, 100 PPI, see the width you got and do the math in order to get the correct resolution. For example, if rendering with -r100 gives you a file 500 pixels wide but you want it to be 1024:

desired_resolution = initial_resolution * desired_width // initial_width

In order to get a file 1024 pixels wide:

>>> 100 * 1024 // 500
204

So you must render the EPS again using -r204 .

Edit 1:

I got the solution from this Question We can set custom width and height using -gNNNNxMMMM but the dpi value crops only a small area. I tried with the usual 72dpi and I got a decent output(I'm not sure if it's perfect or not). Now I need to find how to execute this command every time when I run the program and provide the custom image size value. :\\

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM