Draw on a rects on a QImage without Showing it

Viewed 192

I want to draw rectangles above an QImage and save the result as png. The minimal Example below should do this.

from PyQt5.QtGui import QImage, QColor, QPainter, QBrush
from PyQt5.QtWidgets import QApplication, QMainWindow, QWidget

import sys

class Window(QMainWindow):

    def __init__(self):
        super().__init__()
        self.title = "PyQt5 Drawing Tutorial"
        self.top = 150
        self.left = 150
        self.width = 500
        self.height = 500
        self.mypainter = MyPainter()
        self.mypainter.create()
        self.InitWindow()
    def InitWindow(self):
        self.setWindowTitle(self.title)
        self.setGeometry(self.top, self.left, self.width, self.height)
        self.show()

class MyPainter(QWidget):
    def __init__(self):
        super().__init__()
        self.img = QImage(25, 25, QImage.Format_RGBA64)
        self.color1 = QColor(255, 0, 0, 255)
        self.color2 = QColor(0, 255, 0, 255)
        self.color3 = QColor(0, 0, 255, 255)
        self.boxes = (
            (2, 2, 10, 10),
            (5, 5, 4, 5),
            (10, 10, 10, 7))

    def create(self):
        self.colors = (
            self.color1,
            self.color2,
            self.color3)
        for idx,  box in enumerate(self.boxes):
            self.color = self.colors[idx]
            self.bndboxSize = box
            self.repaint()
        self.img.save("myImg.png")

    def paintEvent(self, event):
        painter = QPainter(self)
        painter.drawImage(self.rect(), self.img)
        painter.setBrush(QBrush(self.color))
        painter.drawRect(self.bndboxSize)

App = QApplication(sys.argv)
window = Window()
sys.exit(App.exec())

What I expected

enter image description here

The black background could also be transparent.

What I got

enter image description here

This is just an image with alphachannel, if your hover you will get the link

What I got (debug mode)

enter image description here

I have no clue how to achive the wanted image.

1 Answers

If you want to create an image then it is not necessary to use the widgets but you have to use QPainter to paint on the QImage. In the OP's attempt it is being painted over the QWidget, and the QImage has only noise.

from PyQt5.QtCore import QRect, Qt
from PyQt5.QtGui import QColor, QGuiApplication, QImage, QPainter


def create_image():
    img = QImage(25, 25, QImage.Format_RGBA64)
    img.fill(Qt.black)

    painter = QPainter(img)

    colors = (QColor(255, 0, 0, 255), QColor(0, 255, 0, 255), QColor(0, 0, 255, 255))
    boxes = (QRect(2, 2, 10, 10), QRect(5, 5, 4, 5), QRect(10, 10, 10, 7))

    for color, box in zip(colors, boxes):
        painter.fillRect(box, color)

    painter.end()

    return img


def main():
    app = QGuiApplication([])
    qimage = create_image()
    qimage.save("myImg.png")


if __name__ == "__main__":
    main()

Output:

enter image description here

Related