DEV Community

Elias Johnstone
Elias Johnstone

Posted on

2 2

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 (1)

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.

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

πŸ‘‹ Kindness is contagious

If this article connected with you, consider tapping ❀️ or leaving a brief comment to share your thoughts!

Okay