Skip to content

ImageOps.exif_transpose raises a KeyError when removing the EXIF orientation tag #5580

@Lucidiot

Description

@Lucidiot

What did you do?

I used ImageOps.exif_transpose on an image with an EXIF orientation tag that should cause a rotation.

What did you expect to happen?

Get a rotated Image with the EXIF orientation removed.

What actually happened?

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
    ImageOps.exif_transpose(img)
  File "/usr/lib/python3.8/site-packages/PIL/ImageOps.py", line 591, in exif_transpose
    del transposed_exif[0x0112]
  File "/usr/lib/python3.8/site-packages/PIL/Image.py", line 3598, in __delitem__
    del self._data[tag]
KeyError: 274

What are your OS, Python and Pillow versions?

  • OS: Ubuntu 20.04.2
  • Python: 3.8.10
  • Pillow: 8.3.0

Steps to reproduce

from PIL import Image, ImageOps
img = Image.new('L', (200, 200))
# Setting the orientation to rotate 270° clockwise
img.getexif()[0x0112] = 6
# this will cause a KeyError
transposed = ImageOps.exif_transpose(img)

Possible fix

From some quick reading, I believe this line is the issue. The EXIF tags in a newly transposed image are empty:

>>> dict(img.transpose(Image.ROTATE_270).getexif())
{}

But the method attempts to remove the orientation tag from this empty dictionary. It seems the change was made to avoid editing the EXIF tags of the original image (#5546), and using copy.copy would probably fix this:

from copy import copy
transposed_exif = copy(exif)
del transposed_exif[0x0112]
print(exif[0x0112])  # it's still there, unmodified

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions