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):
        img =
    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.

Latest comments (2)

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.

Regex for lazy developers

regex for lazy devs

You know who you are. Sorry for the callout 😆