2

Consider simple PyQt4 app, loading picture with QPixmap and scaling with ratio.

Crucial part of code:

from PyQt4 import QtGui, QtCore
(...)
pixmap = QtGui.QPixmap("example.jpg")
pixmap = pixmap.scaled(1100, 1800, QtCore.Qt.KeepAspectRatio)

I've been surprised when I saw my photos in wrong rotation.

I suppose, the reason is that photos contain EXIF information about camera position, which should be considered and rotation applied:

$ exiftool example.jpg  | grep -i rot
Orientation                     : Rotate 270 CW
Auto Rotate                     : Rotate 270 CW
Rotation                        : 270

How to make this with PyQt4, staying close to original short form of program... preferably short&sweet and pythonic way?

Community
  • 1
  • 1
Grzegorz Wierzowiecki
  • 10,545
  • 9
  • 50
  • 88

2 Answers2

3

You need a way to read and parse the EXIF information. (Py)Qt doesn't have that functionality built-in. But there are nice Python tools out there, like pyexiv2, EXIF.py, PyExifTool.

Once you get the rotation angle, then it's easy to apply it to your QPixmap:

pixmap = pixmap.scaled(1100, 1800, QtCore.Qt.KeepAspectRatio)
pixmap = pixmap.transformed(QtGui.QTransform().rotate(angle))
Avaris
  • 35,883
  • 7
  • 81
  • 72
1

It's not most elegant approach, but I've found exiftool to be installed on most systems I use, while packages like pyexiv2 not necessarily.

I used exiftool, by using wrapper class proposed at : https://stackoverflow.com/a/10075210/544721 (note: in order to use wrapper with Py3k you need to add .encode() and .decode() in appropriate places for str<->bytes conversion)

pixmap = QtGui.QPixmap('example.jpg')
with ExifTool() as e:
    exif_metadata = e.get_metadata('example.jpg')
    picture_orientation_code = exif_metadata[0]['EXIF:Orientation']
if picture_orientation_code == 8:
    pixmap = pixmap.transformed(QtGui.QTransform().rotate(270))
elif picture_orientation_code == 6:
    pixmap = pixmap.transformed(QtGui.QTransform().rotate(90))
pixmap = pixmap.scaled(1100, 1600, QtCore.Qt.KeepAspectRatio)

Still - I do not consider it as most elegant, but I hope this answer might help other readers until better solution appear.

Community
  • 1
  • 1
Grzegorz Wierzowiecki
  • 10,545
  • 9
  • 50
  • 88