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
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)
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.