[英]PyQt4 QPixmap Rotating Jpg according to EXIF
考慮簡單的PyQt4
應用程序,使用QPixmap
加載圖片並按比例縮放 。
代碼的關鍵部分:
from PyQt4 import QtGui, QtCore
(...)
pixmap = QtGui.QPixmap("example.jpg")
pixmap = pixmap.scaled(1100, 1800, QtCore.Qt.KeepAspectRatio)
當我看到我的照片旋轉錯誤時,我感到很驚訝。
我想,原因是照片包含有關相機位置的EXIF
信息,應該考慮並應用旋轉:
$ exiftool example.jpg | grep -i rot
Orientation : Rotate 270 CW
Auto Rotate : Rotate 270 CW
Rotation : 270
如何使用PyQt4
實現這一點,保持接近原始的短程序...最好是簡短的甜蜜和pythonic方式?
您需要一種方法來讀取和解析EXIF信息。 (Py)Qt沒有內置的功能。 但是有很好的Python工具,比如pyexiv2
, EXIF.py
, PyExifTool
。
獲得旋轉角度后,可以很容易地將其應用到QPixmap
:
pixmap = pixmap.scaled(1100, 1800, QtCore.Qt.KeepAspectRatio)
pixmap = pixmap.transformed(QtGui.QTransform().rotate(angle))
這不是最優雅的方式,但我發現exiftool
被安裝在我使用最多的系統,而包,比如pyexiv2
不一定。
我使用exiftool
,使用在以下網址提出的包裝類: https ://stackoverflow.com/a/10075210/544721(注意:為了使用Py3k的包裝器,你需要在適當的地方添加.encode()
和.decode()
用於str<->bytes
轉換)
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)
仍然 - 我不認為它是最優雅的,但我希望這個答案可以幫助其他讀者,直到出現更好的解決方案。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.