71

After loading an image file with PIL.Image, how can I determine whether the image file is a PNG/JPG/BMP/GIF? I understand very little about these file formats, can PIL get the format metadata from the file header? Or does it need to 'analyze' the data within the file?

If PIL doesn't provide such an API, is there any python library that does?

NeoWang
  • 17,361
  • 24
  • 78
  • 126

1 Answers1

114

Try:

from PIL import Image

img = Image.open(filename)
print(img.format)  # 'JPEG'

More info

Martin Thoma
  • 124,992
  • 159
  • 614
  • 958
Mikko Ohtamaa
  • 82,057
  • 50
  • 264
  • 435
  • 2
    I guess this attribute is just the file extension, or `None` if the image is constructed with raw data. The file extension is not always available in my case. – NeoWang Sep 20 '15 at 13:04
  • 7
    Please do not guess, but refer to the documentation how the file format is determined. If the PIL reads the image file it must make a choice which decoder is used and this information is exposed through format attribute. – Mikko Ohtamaa Sep 20 '15 at 13:05
  • 49
    For anyone else coming along... you can get the mimetype by doing `Image.MIME[img.format]` – Tim Tisdall Mar 11 '16 at 16:56
  • 3
    is there a more lightweight version of this? for instance looking only at the header or metadata instead of opening the image? – claude computing Aug 23 '18 at 19:33
  • You can use `imghdr`'s `imghdr.what(filename)` function, but it seems to be a bit buggy if extra header info is included in JPEGs (and possibly other formats). – Max Candocia Nov 09 '18 at 21:40
  • 5
    Pillow provides `im.get_format_mimetype()` for getting image mimetype – radioxoma Feb 05 '21 at 22:34
  • it returns wrong value for webp, it returns jpeg instead – TomSawyer Mar 04 '21 at 19:21
  • @TomSawyer smells like a bug, I suggest checking the issue tracker and if the issue does not exist then open a new one – Mikko Ohtamaa Mar 05 '21 at 10:45