DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Elias Johnstone
Elias Johnstone

Posted on

Check if a jpg/jpeg image is corrupt with Pillow

Here is a short code example to check if a jpg/jpeg have their ending bytes or if the file is incomplete or corrupt.

from PIL import Image

def verify_jpeg_image(file_path):
    try:
        img = Image.open(file_path)
        img.getdata()[0]
    except OSError:
        return False
    return True
Enter fullscreen mode Exit fullscreen mode

I have seen solutions using scikit-image, but if you don't need scikit-image to do anything else, you can go for the library that scikit-image uses instead. This way you get fewer dependencies.

Top comments (2)

Collapse
 
eliasj profile image
Elias Johnstone

The image is corrupt when there are missing parts of the image. Jpg/jpeg have two bytes that markΒ the end of the image. We check if those bytes are at the end of the file. When the file is missing the end bytes, you can see this in some images that have gray areas at the bottom.

Some image readers are strict end don't show those files and some don't care like web browsers. If you do image analysisΒ you want to have the whole image to work whit.

🌚 Friends don't let friends browse without dark mode.

Sorry, it's true.