手动设置 Exif 属性 并在 Python 中保持图像的原始宽度和高度

Manually set Exif property and maintain image's original width and height in Python

当我在 python 中执行 Image.open 时,它有时会翻转图像的宽度和高度。经过一些研究(参见 post 的解释),似乎如果图像有 Exif Orientation metadata 与之关联,那么这将导致尊重 属性 的应用程序旋转它。

因此,首先我通过执行

来测试图像的 Exif 属性
identify -verbose image.JPG | grep Orientation

它 returns 6,这意味着图像有 属性 因此将被翻转。如果响应是 1,则图像没有 Exif Orientation metadata,因此不会翻转。由于我不想翻转图像,因此我尝试根据 post 的建议手动设置 Exif property

所以我尝试在我的代码中手动设置 orientation.exif.primary.Orientation[0] = 1。像这样:

from PIL import Image
import pexif


orientation = pexif.JpegFile.fromFile('image.JPG')

print("BEFORE:")
print(orientation.exif.primary.Orientation[0])

orientation.exif.primary.Orientation[0] = 1

print("AFTER:")
print(orientation.exif.primary.Orientation[0])


img = Image.open('image.JPG')
print(img.size)

这在 AFTER 之后更正了打印 1 但是,它实际上并没有在现实生活中将其设置为 1 因为当我 运行又是identify -verbose image.JPG | grep Orientation,还是显示6。那么我该如何真正解决这个问题而不翻转图像的宽度和高度呢?

我不以此为荣。 Superuser 的 post 解决了我的问题。

修复:

import os
os.system("exiftool -Orientation=1 -n image.JPG")

这会将实际图像的方向设置为 1。我在原始问题中的代码更改了我创建的图像对象的方向,而不是实际图像本身。