1-问题描述:
用图片软件打开查看一个文件夹下的所有图片时:分辨率均为1240*1680
但是用python的PIL打开查看时,有些图像分辨率变成了1680*1240
2-原因:
一些图像编辑软件或库在处理图像时,可能会根据图像的方向进行不同旋转显示。
需要通过旋转图像以匹配方向:有时候,图像的 EXIF 数据可能会影响其显示方向。在处理图像时,可以使用 EXIF 数据来正确调整图像的方向
from PIL import Image, ExifTags
def correct_image_orientation(image_path):
img = Image.open(image_path)
try:
exif = img._getexif()
if exif is not None:
for orientation in ExifTags.TAGS.keys():
if ExifTags.TAGS[orientation] == 'Orientation':
break
exif_orientation = exif.get(orientation, 1)
if exif_orientation == 3:
img = img.rotate(180, expand=True)
elif exif_orientation == 6:
img = img.rotate(270, expand=True)
elif exif_orientation == 8:
img = img.rotate(90, expand=True)
except (AttributeError, KeyError, IndexError):
# 没有 EXIF 数据或其他错误
pass
return img
# 示例路径
image_path = 'path_to_your_image.jpg'
# 纠正方向后的图像
corrected_img = correct_image_orientation(image_path)
corrected_img.show()
# 打印纠正后图像的分辨率
print(f'Corrected image size: {corrected_img.size}')
这样可以保证读取进来的图片和用图片软件打开查看的分辨率一致。