Wednesday, May 12, 2021

Rotating an image in PyQt5

 Code below slightly differs from [ 1 ] , which in turn references original idea proposed in [ 2 ] .  Code below provides ability to traverse the folders and select desired image.  Code in [ 1 ] requires the complete path to "jpeg" file to be submitted as command line argument.export

To suppress QT5 buggy warning add to .bashrc

export QT_LOGGING_RULES='*.debug=false;qt.qpa.*=false'

#!/usr/bin/python3


from PyQt5.QtGui import QPixmap, QImage, QTransform
from PyQt5.QtWidgets import QApplication, QWidget, QFileDialog
from PyQt5.QtWidgets import QLabel
from PyQt5.QtCore import Qt, QSize

class ImageRotate(QWidget):
    def __init__(self, image_path, parent=None):
        super().__init__(parent)
        self.label = QLabel(self)
        self.image = QImage(image_path)  
        self.angle = 0

        self.label.setAlignment(Qt.AlignCenter)  
        pm = QPixmap(self.image)
        self.resize(pm.width(), pm.height())  
        self.label.setPixmap(pm)
        self.setWindowTitle('PyQt5 Picture Rotation')

    def keyPressEvent(self, event):
        # on any key
        self.angle += 45 if event.key() == Qt.Key_Down else -45
        trs = QTransform().rotate(self.angle)
        self.label.setPixmap(QPixmap(self.image).transformed(trs))
        return super().keyPressEvent(event)


if __name__ == '__main__':
    import sys
    from  PyQt5.QtWidgets import QApplication, QFileDialog

    app = QApplication(sys.argv)
    qf = QFileDialog()
    fn = qf.getOpenFileName(None, 'Select file', '/',
        'All files (*);; Pictures (*.jpg *.png *.gif *.tif)')[0]
    w = ImageRotate(fn)
    w.move(app.desktop().screen().rect().center() - w.rect().center())
    w.show()
    sys.exit(app.exec_())

No comments:

Post a Comment