Created
February 10, 2020 17:41
-
-
Save uuklanger/4824ffb6c053e8163b8dc00621fb31e5 to your computer and use it in GitHub Desktop.
HOWTO - Check to see if File is Image
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
# | |
# http://www.blog.pythonlibrary.org/2020/02/09/how-to-check-if-a-file-is-a-valid-image-with-python/ | |
# | |
import imghdr # for imghdr | |
from PIL import Image # for Image.open | |
path = 'python.jpg' | |
imghdr.what(path) | |
# returns 'jpeg' | |
path = 'python.png' | |
imghdr.what(path) | |
# returns 'png' | |
img = Image.open('all_python.jpg') | |
img.format | |
# returns 'JPEG' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Be careful! This code only detects the following image formats:
rgb, gif, pbm, pgm, ppm, tiff, rast, xbm, jpeg, bmp, png, webp, exr
See the answers for this question: https://stackoverflow.com/questions/889333/how-to-check-if-a-file-is-a-valid-image-file