3

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)
user984003
  • 23,717
  • 51
  • 158
  • 250

1 Answers1

5

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']
Salem
  • 12,060
  • 3
  • 30
  • 50