PythonでExif読み込んで写真を回転させる方法

Exifで悲しいことになった時のメモ。

PILではExifの読み込みはできても書き込みはできなかったので、力技すぎるなー、と思いつつ下記の方法で対応。

from PIL import Image

_image = Image.open('/path/to/imagefile.jpg')
_orientation = _image._getexif()[274]

if _orientation == 6:
    _image = _image.rotate(-90)

elif _orientation == 8:
    _image = _image.rotate(-270)

elif _orientation == 3:
    _image = _image.rotate(180)

_image.save('/path/to/imagefile_rotated.jpg', 'JPEG')

Exifの値読み込んで、それを参考にしてPILで回転、保存。

PILで保存してあげればExifの情報は全部消え去るので、Exif対応のビューワーで開いた時に困ったことになることもなし。つーかExif全部消されるっていうのもどうかと。

Pillowにフォークされて変わるのかな。今回使ったのもPillowなんだけど。

Python2.7.5、Pillow2.3.1です。