2012-08-26 68 views
7

我在一個web應用程序中使用Django + PIL +亞馬遜boto。用戶發送圖片並且webapp顯示它。大多數人都會發送手機拍攝的照片。有時,圖像顯示方向錯誤。有沒有辦法使用PIL或Django的ImageField從圖像中獲取元信息並使用它來將圖像旋轉到正確的方向?使用PIL自動旋轉拍攝的手機和accelorometer

+1

繼承人一個線程,也許可以幫助你:HTTP://stackoverflow.com/questions/1606587/how-to-use-pil-調整大小和應用旋轉exif信息的文件 – Jingo

+0

這可能會幫助你http://stackoverflow.com/questions/4228530/pil-thumbnail-is-rotating-my-image – Rakesh

回答

3

試試這個獲取EXIF信息。 N.B .: _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] 

因爲我在我的硬盤上發現了一個隨機圖像,由此產生:

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 

這是你想要的Orientation值。它的含義可以在例如在exif orientation page

原始exif數據可從Image.info['exif']以字符串形式獲得。 旋轉可以用rotate()方法完成。

我不知道使用PIL更改EXIF數據的方法,而不是更改原始數據。

3

我使用django-imagekit用於處理圖像,然後使用imagekit.processors.Transpose

from imagekit.models import ImageSpecField 
from imagekit.processors import ResizeToFill, Transpose, SmartResize 

class UserProfile(models.Model): 
    avatar = models.ImageField(upload_to='upload/avatars', max_length=255, blank=True, null=True) 
    avatar_thumbnail = ImageSpecField(
    source='avatar', 
    processors = [Transpose(),SmartResize(200, 200)], 
    format = 'JPEG', 
    options = {'quality': 75} 
) 
相關問題