7

I am using Django + PIL + Amazon boto in a web app. The user sends in the picture and the webapp displays it. Mostly, people send in photo taken from their cell phone. Sometimes, the image is displayed in the wrong orientation. Is there a way to use PIL or Django's ImageField to get the meta information from the image and to use it to rotate the image to the correct orientation?

Alexis
  • 23,545
  • 19
  • 104
  • 143
  • 1
    Heres a thread that maybe can help you:http://stackoverflow.com/questions/1606587/how-to-use-pil-to-resize-and-apply-rotation-exif-information-to-the-file – Jingo Aug 26 '12 at 20:30
  • This might help you http://stackoverflow.com/questions/4228530/pil-thumbnail-is-rotating-my-image – Rakesh Aug 27 '12 at 06:12

2 Answers2

4

I'm using django-imagekit for processing images then using 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}
  )
3

Try this for getting the EXIF info. N.B.: the _getexif() method belongs to the JPEG plugin. It won't exist in other types of images.

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]

For a random image I found on my harddisk, this produced:

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

It is the Orientation value that you want. Its meaning can be found e.g. on the exif orientation page.

The raw exif data is available as a string from Image.info['exif']. Rotation can be accomplished with the rotate() method.

I'm not aware of a method to change the EXIF data using PIL, other than changing the raw data.

Roland Smith
  • 42,427
  • 3
  • 64
  • 94