156

I am currently using PIL.

from PIL import Image

try:
    im = Image.open(filename)
    # do stuff
except IOError:
    # filename not an image file

However, while this sufficiently covers most cases, some image files like, xcf, svg and psd are not being detected. PSD files throw an OverflowError exception.

Is there someway I could include them as well?

7
  • Well, I do not know about the insides of psd, but I, sure, know that, as a matter of fact, svg is not an image file per se, -- it is based on xml, so it is, essentially, a plain text file.
    – shylent
    Commented May 20, 2009 at 18:03
  • 28
    It's not particularly common practice to close duplicates across different languages. If you can't find any other Python questions with this leave it open as there could be Python-specific solutions that people want to post that did not make it to the question you posted. Commented May 20, 2009 at 18:09
  • yes, first of all I was really hoping for a python lib I didnt know about :P and then as ben pointed out, just the magic numbers doesnt validate the entire image.
    – Sujoy
    Commented May 20, 2009 at 18:14
  • @Sujoy, validating an entire image is nearly impossible, unless you already have a copy of it, because the computer can't tell the difference between a correct colour pixel, and a garbled set of 1s and 0s, as long as all the control (magic numbers) are correct.
    – DevinB
    Commented May 20, 2009 at 18:25
  • @devinb, agreed, i will just get the magic numbers and be done with it unless someone else comes up with something better to call for a refactor :)
    – Sujoy
    Commented May 20, 2009 at 18:31

11 Answers 11

259

You can use the builtin imghdr module. From its documentation:

The imghdr module determines the type of image contained in a file or byte stream.

This is how you use it:

>>> import imghdr
>>> imghdr.what('/tmp/bass')
'gif'

Note: imghdr is deprecated as of Python 3.11 because it only supported a small number of file formats.

13
  • 6
    yes imghdr works for most image formats but not all. as per my original problem with svg, xcf and psd files, well those are undetected in imghdr as well
    – Sujoy
    Commented May 26, 2009 at 12:54
  • 2
    Your answer is actually better, thanks. Like someone above said ...but solving a problem 99% of the way is often better then not solving it at all..
    – RinkyPinku
    Commented Jun 3, 2015 at 11:54
  • 4
    Worth to note: imghdr.what(path) returns None if given path is not recognized image file type. List of currently recognized image types: rgb, gif, pbm, pgm, ppm, tiff, rast, xbm, jpeg, bmp, png, webp, exr. Commented Apr 6, 2016 at 15:29
  • 3
    I have found that occasionally imghdr.what(path) returns None even if the file is a valid image, particularly for jpegs. Commented Jan 2, 2017 at 19:32
  • 4
    Be careful! A valid hdr doesn't mean a valid image (e.g. the image bytes may have been scrambled!) Commented Nov 30, 2017 at 13:37
56

In addition to what Brian is suggesting you could use PIL's verify method to check if the file is broken.

im.verify()

Attempts to determine if the file is broken, without actually decoding the image data. If this method finds any problems, it raises suitable exceptions. This method only works on a newly opened image; if the image has already been loaded, the result is undefined. Also, if you need to load the image after using this method, you must reopen the image file. Attributes

10
  • 1
    well the main problem is that svg,xcf and psd files cannot be opened with Image.open() hence, no chance of verifying with im.verify()
    – Sujoy
    Commented May 20, 2009 at 19:07
  • 31
    My god the PIL documentation is terrible. What is exactly is a "suitable exception"?
    – Timmmm
    Commented Jul 26, 2012 at 19:45
  • Here's the link to the Pillow documentation for Image.verify(). Unfortunately, it's no better, and it looks like they just lifted the paragraph above without adding anything. Commented Aug 8, 2014 at 18:34
  • I've seen verify raise SyntaxError for corrupt png files
    – Carl
    Commented Nov 20, 2015 at 3:41
  • 10
    mmh the source code seems to verify... nothing! pillow.readthedocs.io/en/latest/_modules/PIL/…
    – Massimo
    Commented Dec 12, 2019 at 21:06
30

Additionally to the PIL image check you can also add file name extension check like this:

filename.lower().endswith(('.png', '.jpg', '.jpeg', '.tiff', '.bmp', '.gif'))

Note that this only checks if the file name has a valid image extension, it does not actually open the image to see if it's a valid image, that's why you need to use additionally PIL or one of the libraries suggested in the other answers.

3
  • 7
    What if the extensions are incorrect in the files? E.g, a text file is saved with .jpg extension or vice versa.
    – hafiz031
    Commented Aug 11, 2020 at 4:00
  • 3
    @hafiz031 To get the actual format you can do from PIL import Image img = Image.open(filename) print(img.format) and then check it like this: img.format.lower() in ['png', 'jpg', 'jpeg', 'tiff', 'bmp', 'gif']
    – tsveti_iko
    Commented Aug 12, 2020 at 11:35
  • Unfortunately this didn't work for me. It is still identifying a corrupted image as a JPEG image. Finally I managed to handle this case in this way (I am using OpenCv): stackoverflow.com/a/63421847/6907424
    – hafiz031
    Commented Aug 15, 2020 at 2:28
17

One option is to use the filetype package.

Installation

python -m pip install filetype

Advantages

  1. Fast: Does its work by loading only the first few bytes of your image (check on the magic number)
  2. Supports different mime type: Images, Videos, Fonts, Audio, Archives.

Example

filetype >= 1.0.7

import filetype

filename = "/path/to/file.jpg"

if filetype.is_image(filename):
    print(f"{filename} is a valid image...")
elif filetype.is_video(filename):
    print(f"{filename} is a valid video...")

filetype <= 1.0.6

import filetype

filename = "/path/to/file.jpg"

if filetype.image(filename):
    print(f"{filename} is a valid image...")
elif filetype.video(filename):
    print(f"{filename} is a valid video...")

Additional information on the official repo: https://github.com/h2non/filetype.py

3
  • Filetype program supports webp format too. Nice!
    – Nav
    Commented Mar 9, 2021 at 10:56
  • Does this module use the mimetype? What, if the file extension is not the actual file type? Commented Dec 21, 2023 at 10:47
  • 1
    From the repository (linked in the answer), filetype is coded in pure Python and relies "Only [on the] first 261 bytes representing the max file header". This makes me think that it does not relies on the file extension, but rather the actual encoding of the image or video. Commented Dec 29, 2023 at 15:54
16

A lot of times the first couple chars will be a magic number for various file formats. You could check for this in addition to your exception checking above.

5
  • 14
    That won't be sufficient if he's really testing for "valid" images; the presence of a magic number doesn't guarantee that the file hasn't been truncated, for example.
    – Ben Blank
    Commented May 20, 2009 at 18:11
  • 1
    excellent advice, now i just need to figure out what those numbers are. thanks :)
    – Sujoy
    Commented May 20, 2009 at 18:11
  • @ben, ouch i didnt think of that yet. thats a good point indeed
    – Sujoy
    Commented May 20, 2009 at 18:12
  • @Ben, how would you expect a library to infer a file has been truncated?
    – DevinB
    Commented May 20, 2009 at 18:25
  • 9
    @Ben Blank: True, but solving a problem 99% of the way is often better then not solving it at all. Commented May 20, 2009 at 21:14
13

Update

I also implemented the following solution in my Python script here on GitHub.

I also verified that damaged files (jpg) frequently are not 'broken' images i.e, a damaged picture file sometimes remains a legit picture file, the original image is lost or altered but you are still able to load it with no errors. But, file truncation cause always errors.

End Update

You can use Python Pillow(PIL) module, with most image formats, to check if a file is a valid and intact image file.

In the case you aim at detecting also broken images, @Nadia Alramli correctly suggests the im.verify() method, but this does not detect all the possible image defects, e.g., im.verify does not detect truncated images (that most viewers often load with a greyed area).

Pillow is able to detect these type of defects too, but you have to apply image manipulation or image decode/recode in or to trigger the check. Finally I suggest to use this code:

from PIL import Image

try:
  im = Image.load(filename)
  im.verify() #I perform also verify, don't know if he sees other types o defects
  im.close() #reload is necessary in my case
  im = Image.load(filename) 
  im.transpose(Image.FLIP_LEFT_RIGHT)
  im.close()
except: 
  #manage excetions here

In case of image defects this code will raise an exception. Please consider that im.verify is about 100 times faster than performing the image manipulation (and I think that flip is one of the cheaper transformations). With this code you are going to verify a set of images at about 10 MBytes/sec with standard Pillow or 40 MBytes/sec with Pillow-SIMD module (modern 2.5Ghz x86_64 CPU).

For the other formats xcf,.. you can use Imagemagick wrapper Wand, the code is as follows: Check the Wand documentation: here, to installation: here

im = wand.image.Image(filename=filename)
temp = im.flip;
im.close()

But, from my experiments Wand does not detect truncated images, I think it loads lacking parts as greyed area without prompting.

I red that Imagemagick has an external command identify that could make the job, but I have not found a way to invoke that function programmatically and I have not tested this route.

I suggest to always perform a preliminary check, check the filesize to not be zero (or very small), is a very cheap idea:

import os

statfile = os.stat(filename)
filesize = statfile.st_size
if filesize == 0:
  #manage here the 'faulty image' case
7

On Linux, you could use python-magic which uses libmagic to identify file formats.

AFAIK, libmagic looks into the file and tries to tell you more about it than just the format, like bitmap dimensions, format version etc.. So you might see this as a superficial test for "validity".

For other definitions of "valid" you might have to write your own tests.

6

You could use the Python bindings to libmagic, python-magic and then check the mime types. This won't tell you if the files are corrupted or intact but it should be able to determine what type of image it is.

3

Adapting from Fabiano and Tiago's answer.

from PIL import Image

def check_img(filename):
    try:
        im = Image.open(filename)
        im.verify()
        im.close()
        im = Image.open(filename) 
        im.transpose(Image.FLIP_LEFT_RIGHT)
        im.close()
        return True
    except: 
        print(filename,'corrupted')
        return False

if not check_img('/dir/image'):
    print('do something')
-4
format = [".jpg",".png",".jpeg"]
 for (path,dirs,files) in os.walk(path):
     for file in files:
         if file.endswith(tuple(format)):
             print(path)
             print ("Valid",file)
         else:
             print(path)
             print("InValid",file)
2
  • 1
    Your code has some indentation issues and won't run properly. Also, consider adding some explanations as to why and how your code solves the problem. Code-only answers by not be so helpful for future readers coming here.
    – Tomerikoo
    Commented Feb 28, 2020 at 12:43
  • Here we have used Agrparser method.
    – rObinradOO
    Commented Mar 5, 2020 at 12:31
-4

Extension of the image can be used to check image file as follows.

import os
for f in os.listdir(folderPath):
    if (".jpg" in f) or (".bmp" in f):
        filePath = os.path.join(folderPath, f)
 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.