使用PIL自动旋转手机和accelorometer拍摄的照片

Ale*_*xis 7 python django django-models python-imaging-library

我在一个网络应用程序中使用Django + PIL + Amazon boto.用户发送图片,webapp显示它.大多数情况下,人们发送从手机拍摄的照片.有时,图像显示方向错误.有没有办法使用PIL或Django的ImageField从图像中获取元信息并使用它来将图像旋转到正确的方向?

Rol*_*ith 3

尝试获取 EXIF 信息。注意:该_getexif()方法属于JPEG插件。它不会存在于其他类型的图像中。

import Image
from PIL.ExifTags import TAGS

im = Image.open('a-jpeg-file.jpg')
exifdict = im._getexif()
if len(exifdict):
    for k in exifdict.keys():
        if k in TAGS.keys():
            print TAGS[k], exifdict[k]
        else:
            print k, exifdict[k]
Run Code Online (Sandbox Code Playgroud)

对于我在硬盘上找到的随机图像,这会产生:

ExifVersion 0221
ComponentsConfiguration 
ApertureValue (4312, 1707)
DateTimeOriginal 2012:07:19 17:33:37
DateTimeDigitized 2012:07:19 17:33:37
41989 35
FlashPixVersion 0100
MeteringMode 5
Flash 32
FocalLength (107, 25)
41986 0
Make Apple
Model iPad
Orientation 1
YCbCrPositioning 1
SubjectLocation (1295, 967, 699, 696)
SensingMethod 2
XResolution (72, 1)
YResolution (72, 1)
ExposureTime (1, 60)
ExposureProgram 2
ColorSpace 1
41990 0
ISOSpeedRatings 80
ResolutionUnit 2
41987 0
FNumber (12, 5)
Software 5.1.1
DateTime 2012:07:19 17:33:37
41994 0
ExifImageWidth 2592
ExifImageHeight 1936
ExifOffset 188
Run Code Online (Sandbox Code Playgroud)

这就是Orientation您想要的值。例如,可以在exif 方向页面上找到其含义。

原始 exif 数据可作为字符串从Image.info['exif']. 通过该方法可以实现旋转rotate()

除了更改原始数据之外,我不知道使用 PIL 更改 EXIF 数据的方法。