I have opened a image in a QHBoxLayout
. I need to crop the opened image and save the cropped image. How I can do this in PySide?
import sys
from PySide import QtGui, QtCore
class Example(QtGui.QWidget):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def initUI(self):
hbox = QtGui.QHBoxLayout(self)
pixmap = QtGui.QPixmap("re.png")
lbl = QtGui.QLabel(self)
lbl.setPixmap(pixmap)
self.rect = QtCore.QRect()
hbox.addWidget(lbl)
self.setLayout(hbox)
self.setGeometry(300, 300, 280, 170)
self.setWindowTitle('Open Image')
self.show()
# Tried here to implement Qpen
#self.painter = QtGui.QPainter(self)
#self.painter.setPen(QtGui.QPen(QtCore.Qt.black, 1, QtCore.Qt.SolidLine));
#self.painter.drawRect(self.rect);
def main():
app = QtGui.QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
I would use QImage's
copy
method:I suggest use class
QtGui.QRubberBand
to select area of image to crop. (PySide aslo implement same PyQt)First, implement method
mouseMoveEvent (self, QMouseEvent)
,mouseReleaseEvent (self, QMouseEvent)
andmousePressEvent (self, QMouseEvent)
(More infomation read inQtGui.QRubberBand
class reference).Next, get last geometry of
QtGui.QRubberBand
to crop image by useQRect QWidget.geometry (self)
.Last, Use
QPixmap QPixmap.copy (self, QRect rect = QRect())
to crop image by put geometry from crop area. And save image it by usebool QPixmap.save (self, QString fileName, str format = None, int quality = -1)
.Example;