Struct error with PIL exif when saving image - how to except this error?

38 views Asked by At

I am opening images with PIL, reading their exif information, compressing the image to the allowed_size, and adding the exif back to the image when I Image.save it. After about 3,000 successes with this process, a file gave me the following struct.error:

'struct.error: 'H' format requires 0 <= number <= 65535'

The struct.error is thrown at img.save step in my (simplified) code here:

from PIL import Image,ExifTags

allowed_size = 123456 #Some Number
fname = 'path/to/file.type'
file_size = os.path.getsize(fname)
new_fname = #secret string

img = Image.open(fname)
exif = img.getexif()
len_exif = len(exif)
if(len_exif >0):
   if file_size > upload_size:
      img.save(new_fname,"JPEG", optimize=True, quality=100,exif=exif) #Decompress first, better for predicting quality value needed for target file size
      #Do other things, resize

I gather that this is an error potentially due to the exif read from the original image being incorrect to what PIL is expecting. Please correct me if I'm wrong.

The question: how do I go about doing a try: and except: with this error? I would like to try saving the file after compression with the exif information and if this struct.error presents itself to skip adding the exif back and just save the file.

**Thank you in advance for any pointers. **What am I missing? Is the exception for this struct.error possible? I'm new to posting here, but I have been reading for years. Please accept my apologies if you need more information to weigh in of if this question is below the standards of the site.

I've tried this:

try:
   img.save(new_fname,"JPEG", optimize=True, quality=100,exif=exif)
except struct.error:
   img.save(new_fname,"JPEG", optimize=True, quality=100)

Expecting an exception and the file to save without exif, but got 'NameError: name 'struct' is not defined.'

Python 3.11

0

There are 0 answers