Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct
Saving an image after painting on it
-
What i am trying to do is be able to draw on an image (specifically rectangles) and then save the image. I have found the following code:
from PyQt5.QtWidgets import * from PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() self.image = QImage("img.png") self.image.scaledToWidth(400) # self.showFullScreen() self.startPos = None self.rect = QRect() self.drawing = False def mousePressEvent(self, event): if event.button() == Qt.LeftButton and not self.drawing: self.startPos = event.pos() self.rect = QRect(self.startPos, self.startPos) self.drawing = True self.update() def mouseMoveEvent(self, event): if self.drawing == True: self.rect = QRect(self.startPos, event.pos()) self.update() def mouseReleaseEvent(self, event): if event.button() == Qt.LeftButton: self.drawing = False def paintEvent(self, event): pen = QPen() pen.setWidth(3) pen.setColor(QColor(255, 0, 0)) brush = QBrush() brush.setColor(QColor(255, 0, 0)) brush.setStyle(Qt.SolidPattern) painter = QPainter(self) painter.drawImage(0, 0, self.image) painter.setBrush(brush) painter.setPen(pen) if not self.rect.isNull(): painter.drawRect(self.rect) painter.end() app = QApplication(sys.argv) window = Window() window.show() sys.exit(app.exec_())
From this forum post: https://discuss.python.org/t/if-mouse-button-event-draw-rectangle-pyqt5/6064/11
However when i try and save the image, it just saves the original without the rectangle. Also, it allows for drawing outside the boundaries of the image which i do not want
How can i fix these issues?
-
Hi,
You have to paint on the QImage if you want these changes to be storable.
You can do that in the method that saves the image. Do the painting on a copy of it and save it after.
-
@SGaist Hi, I'm not really sure how i would do that, can you point me in the right direction?
-
Well:
- create a copy of the image
- create a QPainter on it
- draw
- call end
- save the copy
-
@SGaist Sorry but i have no idea how to call a qpainter on the image as well as creating a copy, can i have some actual code?
Appeciate the help
Just to add i understand what you're saying so you don't need to simplify it , just not how to implement it with pyqt
-
For the copy, please read the class documentation. It's QImage::copy.
For painting on the QImage:
painter = QPainter(image) # paint what you want painter.end()
-
This post is deleted!