当Exif数据为None时,如何使用python PIL获取图像方向

时间:2019-08-05 05:55:49

标签: python-3.x python-imaging-library exif

嗨,我在上传图片时遇到了一个问题。当我上传图片时,许多提示都会改变方向。因此,在这种情况下,我会使用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数据。所以我对此有疑问。

  1. 在那段时间里,我需要在脚本中更改什么?当我得到方向时 图片Exif标签“无”?

请任何人给我建议。 谢谢。

0 个答案:

没有答案