Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python PIL: verify extension before saving

Is there a way to check whether an extension is okay for PIL before attempting to save an image?

In the example below, if ext = "jpg" then it works fine, but if it's "xxx" then I get a keyError.

my_image.save(filepath + ext)
like image 652
user984003 Avatar asked Jun 30 '26 16:06

user984003


1 Answers

You can use a try/except to try to save your image in your preferred format, and if it fails do something else (save in a fallback format, for example)

try:
    my_image.save(filepath + ".png")
except KeyError: # cannot save as PNG, save as JPEG then
    my_image.save(filepath + ".jpg")

Or check you can use the extension:

>>> import Image
>>> Image.init()
>>> Image.SAVE.keys() # output from my system
['PCX', 'HDF5', 'TIFF', 'BUFR', 'SPIDER', 'JPEG', 'MSP', 'XBM', 'GIF', 'BMP', 'TGA', 'IM', 'GRIB', 'PPM', 'FITS', 'PDF', 'PALM', 'EPS', 'WMF', 'PNG']
like image 197
Salem Avatar answered Jul 02 '26 08:07

Salem



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!