I am currently trying to handle properly truncated images (for instance knowing what percentage of the image is truncated etc).
For that I truncate images myself, so I think it can help to understand what a truncated image is:
import os
from PIL import Image, ImageOps, ImageFile
ImageFile.LOAD_TRUNCATED_IMAGES = False # to be sure that truncated image raise an error
# In Jupyter notebook I use IPython for displaying images.
# Keep in mind that IPython.display.display catches everything:
# display but also exceptions and errors
# so you cannot catch exceptions on a try: display
from IPython.display import display
# Display image
image = Image.open(image_path)
display(image)
##### Truncate the image to 80% of its size #####
# get info about image file size (in bytes)
image_file_size = os.path.getsize(image_path)
print(f"image file size: {image_file_size}")
# compute 80% of the image size (file version of the image, not pixels)
truncated_image_size = int(image_file_size * 0.8)
# open image, as a file (not an image), in append mode, and truncate it
with open(image_path,"a") as image_file:
image_file.truncate(truncated_image_size)
################################################
# Display the truncated image
image = Image.open(image_path)
try:
image_bytes = image_truncated.tobytes() # Raise an error if image is truncated
except OSError as e:
print(f"exception catched: {e}")
# The exception write a number of unread bytes, but which does not correspond to the actual number of missing pixels
# Actually display truncated image
ImageFile.LOAD_TRUNCATED_IMAGES = True
display(image)
##### Compute actual number of missing pixels #####
img_as_pixels = image_truncated.getdata()
# Check which pixels are grey (missing values)
grey_pixel_tuple = (128, 128, 128)
is_grey_pixels = [True if pixel == grey_pixel_tuple else False for pixel in img_as_list]
# Get the position of the last "not grey" pixel
last_not_truncated_pixel = next(i for i in reversed(range(len(is_grey_pixels))) if is_grey_pixels[i] == False)
# Compute the percentage of the image not missing
percentage_of_available_image = last_not_truncated_pixel / len(img_reshape)
print(f"percentage_of_available_image: {percentage_of_available_image}")
ImageFile.LOAD_TRUNCATED_IMAGES = False