PIL can be used to check if an image file is corrupted by attempting to open and analyze the image. The “Image” module’s “open()” function is used to open the image file, then “verify()” method is called on the opened image object. If the image file is corrupted, these functions will raise an IOError exception. Here’s a simple code example:
from PIL import Image
def is_image_corrupted(image_path):
try:
img = Image.open(image_path)
img.verify()
return False
except IOError:
return True
This function returns False when the image isn’t corrupted and True otherwise.