嗨,我在上传图片时遇到了一个问题。当我上传图片时,许多提示都会改变方向。因此,在这种情况下,我会使用PIL库提取exif数据。我得到了图像的方向。并据此旋转图像。我检查了两三个图像。我获得了许多Exif标签的图像无。所以我没有得到图像的方向。 我尝试使用此代码python代码。
from PIL import Image
def FixImage(img, max_width=None, max_height=None):
ORIENT = {
2: (0, 1),
3: (180, 0),
4: (0, 2),
5: (90, 1),
6: (270, 0),
7: (270, 1),
8: (90, 0),
}
assert isinstance(img, Image.Image), "Invalid 'img' parameter to fix_image()"
img_format = img.format
# fix img orientation (issue with jpegs taken by cams; phones in particular):
try:
orient = img._getexif()[274]
except (AttributeError, KeyError, TypeError, ValueError):
orient = 1 # default (normal)
if orient in ORIENT:
(rotate, mirror) = ORIENT[orient]
if rotate:
img = img.rotate(rotate)
if mirror == 1:
img = img.transpose(Image.FLIP_LEFT_RIGHT)
elif mirror == 2:
img = img.transpose(Image.FLIP_TOP_BOTTOM)
# strip image
data = img.getdata()
palette = img.getpalette()
img = Image.new(img.mode, img.size)
img.putdata(data)
if palette:
img.putpalette(palette)
# resize image (if necessary):
(width, height) = img.size
if max_width and width > max_width and (not max_height or width*max_height >= height*max_width): # width is constraint
img = img.resize((max_width, round(height*max_width/width)), Image.LANCZOS)
elif max_height and height > max_height: # height is constraint
img = img.resize((round(width*max_height/height), max_height), Image.LANCZOS)
img.format = img_format # preserve orig format
return img
因此在此python脚本中,如果我在exif数据中找到方向,则能够旋转图像。如果我没有exif数据。所以我对此有疑问。
请任何人给我建议。 谢谢。