且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何裁剪图像并保存?

更新时间:2023-12-05 15:58:04

我建议使用类 QtGui.QRubberBand 选择要裁剪的图像区域。 (PySide还实现了与PyQt相同的功能)

I suggest use class QtGui.QRubberBand to select area of image to crop. (PySide also implements the same functionality as PyQt)

首先,实现方法 mouseMoveEvent(自己,QMouseEvent) mouseReleaseEvent(自身,QMouseEvent) mousePressEvent(自身,QMouseEvent)(更多信息请参见 QtGui .QRubberBand 类参考)。

First, implement method mouseMoveEvent (self, QMouseEvent), mouseReleaseEvent (self, QMouseEvent) and mousePressEvent (self, QMouseEvent) (More infomation read in QtGui.QRubberBand class reference).

接下来,获取 QtGui.QRubberBand 的最后一个几何使用 QRect QWidget.geometry(自身)来裁剪图像

Next, get last geometry of QtGui.QRubberBand to crop image by use QRect QWidget.geometry (self).

最后,使用> $code> QPixmap QPixmap.copy(自身,QRect rect = QRect()) 通过从作物面积。并使用 bool QPixmap.save(self ,QString fileName,str格式= None,int quality = -1)

Last, Use QPixmap QPixmap.copy (self, QRect rect = QRect()) to crop image by put geometry from crop area. And save image it by use bool QPixmap.save (self, QString fileName, str format = None, int quality = -1).

示例;

import sys
from PyQt4 import QtGui, QtCore

class QExampleLabel (QtGui.QLabel):
    def __init__(self, parentQWidget = None):
        super(QExampleLabel, self).__init__(parentQWidget)
        self.initUI()

    def initUI (self):
        self.setPixmap(QtGui.QPixmap('input.png'))

    def mousePressEvent (self, eventQMouseEvent):
        self.originQPoint = eventQMouseEvent.pos()
        self.currentQRubberBand = QtGui.QRubberBand(QtGui.QRubberBand.Rectangle, self)
        self.currentQRubberBand.setGeometry(QtCore.QRect(self.originQPoint, QtCore.QSize()))
        self.currentQRubberBand.show()

    def mouseMoveEvent (self, eventQMouseEvent):
        self.currentQRubberBand.setGeometry(QtCore.QRect(self.originQPoint, eventQMouseEvent.pos()).normalized())

    def mouseReleaseEvent (self, eventQMouseEvent):
        self.currentQRubberBand.hide()
        currentQRect = self.currentQRubberBand.geometry()
        self.currentQRubberBand.deleteLater()
        cropQPixmap = self.pixmap().copy(currentQRect)
        cropQPixmap.save('output.png')

if __name__ == '__main__':
    myQApplication = QtGui.QApplication(sys.argv)
    myQExampleLabel = QExampleLabel()
    myQExampleLabel.show()
    sys.exit(myQApplication.exec_())