NeoWang
NeoWang

Reputation: 18513

How to get the format of image with PIL?

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?

Upvotes: 77

Views: 86310

Answers (2)

leafmeal
leafmeal

Reputation: 2092

Beware! If the image you are trying to get the format from an image that was created from a copy(), the format will be None.

From the docs

Copies of the image will contain data loaded from the file, but not the file itself, meaning that it can no longer be considered to be in the original format. So if copy() is called on an image, or another method internally creates a copy of the image, then any methods or attributes specific to the format will no longer be present. The fp (file pointer) attribute will no longer be present, and the format attribute will be None.

Methods that create an implicit copy include:

  • convert()
  • crop()
  • remap_palette()
  • resize()
  • reduce()
  • rotate()
  • split()
  • these were all I found as of today, but others may be added

For example:

img = Image.open(filename)
print(img.format)  # 'JPEG'
img2 = img.copy()
print(img2.format)  # None
print(img.rotate(90, expand=True).format).  # None

So if you need to get the format from a copy, you need to look to the original image.

Upvotes: 1

Mikko Ohtamaa
Mikko Ohtamaa

Reputation: 83758

Try:

from PIL import Image

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

More info

Upvotes: 121

Related Questions