Pillow supports EPS, but cannot write it with alpha channel (RGBA
, LA
)
https://pillow.readthedocs.io/en/stable/handbook/image-file-formats.html?highlight=eps#eps:
Pillow identifies EPS files containing image data, and can read files
that contain embedded raster images (ImageData descriptors). If
Ghostscript is available, other EPS files can be read as well. The EPS
driver can also write EPS images. 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. The
EPS driver can write images in L, RGB and CMYK modes.
Helped for me to convert the image to RGB
mode before saving
from PIL import Image
fig = Image.open("Image1.png")
if fig.mode in ('RGBA', 'LA'):
# https://pillow.readthedocs.io/en/stable/handbook/image-file-formats.html?highlight=eps#eps
print('Current figure mode "{}" cannot be directly saved to .eps and should be converted (e.g. to "RGB")'.format(fig.mode))
fig = fig.convert('RGB')
out_fig = "Image1.eps"
fig.save(out_fig)
fig.close()
But sometimes I had problems: got black background in .eps
instead of transparent .png
. For me helped remove_transparency()
function from https://stackoverflow.com/a/35859141/7444782 to substitute the transparent background to a specified color (white by default)
from PIL import Image
def remove_transparency(im, bg_color=(255, 255, 255)):
"""
Taken from https://stackoverflow.com/a/35859141/7444782
"""
# Only process if image has transparency (http://stackoverflow.com/a/1963146)
if im.mode in ('RGBA', 'LA') or (im.mode == 'P' and 'transparency' in im.info):
# Need to convert to RGBA if LA format due to a bug in PIL (http://stackoverflow.com/a/1963146)
alpha = im.convert('RGBA').split()[-1]
# Create a new background image of our matt color.
# Must be RGBA because paste requires both images have the same format
# (http://stackoverflow.com/a/8720632 and http://stackoverflow.com/a/9459208)
bg = Image.new("RGBA", im.size, bg_color + (255,))
bg.paste(im, mask=alpha)
return bg
else:
return im
fig = Image.open("Image1.png")
if fig.mode in ('RGBA', 'LA'):
# https://pillow.readthedocs.io/en/stable/handbook/image-file-formats.html?highlight=eps#eps
print('Current figure mode "{}" cannot be directly saved to .eps and should be converted (e.g. to "RGB")'.format(fig.mode))
fig = remove_transparency(fig)
fig = fig.convert('RGB')
out_fig = "Image1.eps"
fig.save(out_fig)
fig.close()