Skip to content

Commit

Permalink
Fix issue with loading some JPG: #3416
Browse files Browse the repository at this point in the history
  • Loading branch information
comfyanonymous committed May 7, 2024
1 parent d7fa417 commit c334122
Showing 1 changed file with 12 additions and 2 deletions.
14 changes: 12 additions & 2 deletions nodes.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
import random
import logging

from PIL import Image, ImageOps, ImageSequence
from PIL import Image, ImageOps, ImageSequence, ImageFile
from PIL.PngImagePlugin import PngInfo

import numpy as np
Expand Down Expand Up @@ -1462,7 +1462,17 @@ def load_image(self, image):
output_images = []
output_masks = []
for i in ImageSequence.Iterator(img):
i = ImageOps.exif_transpose(i)
prev_value = None
try:
i = ImageOps.exif_transpose(i)
except OSError:
prev_value = ImageFile.LOAD_TRUNCATED_IMAGES
ImageFile.LOAD_TRUNCATED_IMAGES = True
i = ImageOps.exif_transpose(i)
finally:
if prev_value is not None:
ImageFile.LOAD_TRUNCATED_IMAGES = prev_value

if i.mode == 'I':
i = i.point(lambda i: i * (1 / 255))
image = i.convert("RGB")
Expand Down

1 comment on commit c334122

@shawnington
Copy link
Contributor

@shawnington shawnington commented on c334122 May 7, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This seems to be related to ICC profile error I committed the fix to, maybe a more generic function that does try except for all PIL functions that could handle meta-data would be useful? A lot of devices embed color related meta-data, and the errors are unlikely to ever be fixed in the Pillow library as they seem to expect color management things to be handled with their ImageCMS module, and PIL seems to throw a fit when using the regular Image module for different image types such as HDR images from phones, images with the ICC profiles etc, LOAD_TRUNCATED_IMAGES seems to fix a lot of the errors.

Maybe something where the operation is injected as a dependency and and the LOAD_TRUNCATED_IMAGES flag is toggled if the operation fails like

def Pil_Helper(fn, arg):
   prev_value = None
   try:
      x = fn(arg)
   except OSError:
      prev_value = ImageFile.LOAD_TRUNCATED_IMAGES
      ImageFile.LOAD_TRUNCATED_IMAGES = True
      x = fn(arg)
   finally:
      if prev_value is not None:
          ImageFile.LOAD_TRUNCATED_IMAGES = prev_value
      return x

to be called like :

img = Pil_Helper(Image.open, file_path)
for i in ImageSequence.Iterator(img):
     i = Pil_Helper(ImageOps.exif_transpose, i)

Then we have a generalized way to wrap functions in the try except to toggle the meta data truncation, and it wont need to be added for every Pil function that is discovered throwing errors because of meta data?

could go in node_helpers.py so that is easily accessible for use in nodes that use PIL also.

Please sign in to comment.