Search code examples
pythonpyqtqtguiqtcore

PyQt: How to Generate a Raster Image with a Custom Message


To generate a solid gray image I'm using:

def generate_image(filepath):
    img = QtGui.QImage(720, 405, QtGui.QImage.Format_RGB32)
    img.fill(QtCore.Qt.gray)
    img.save(filepath, 'JPG')

I wonder how difficult it would be to customize this function to layer a simple text message on top of the gray background. I appreciate an input!


Solution

  • You just need to use a QPainter to draw on the image:

    def generate_image(filepath, text='Hello World!', color='red', font=None):
        img = QtGui.QImage(720, 405, QtGui.QImage.Format_RGB32)
        img.fill(QtCore.Qt.gray)
        painter = QtGui.QPainter(img)
        painter.setPen(QtGui.QColor(color))
        if font is None:
            font = painter.font()
            font.setBold(True)
            font.setPointSize(24)
        painter.setFont(font)
        painter.drawText(img.rect(), QtCore.Qt.AlignCenter, text)
        painter.end()
        return img.save(filepath, 'JPG')