Reputation: 18513
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
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. Thefp
(file pointer) attribute will no longer be present, and theformat
attribute will beNone
.
Methods that create an implicit copy include:
convert()
crop()
remap_palette()
resize()
reduce()
rotate()
split()
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
Reputation: 83758
Try:
from PIL import Image
img = Image.open(filename)
print(img.format) # 'JPEG'
More info
https://pillow.readthedocs.io/en/latest/reference/Image.html#PIL.Image.Image.format
https://pillow.readthedocs.io/en/latest/handbook/image-file-formats.html
Upvotes: 121