Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Qt/PyQt(/Other?): How do I change specific colors in a pixmap?

Tags:

qt

pyqt

pixmap

How do I change specific colors in a pixmap? For example, I have a pixmap with white and black pixels, and I want to change all white pixels to blue, but leave the black ones alone. Or maybe change the black to white and the white to blue... [I am searching for a solution in Qt/PyQt, but maybe this is a general question as to how pixmaps are handled/composed.]

like image 844
Jeff Avatar asked Dec 25 '11 09:12

Jeff


1 Answers

You can use createMaskFromColor to create a bitmap for the white pixels, then use drawPixmap to overwrite them with another color.

    pix = QPixmap("test.png")
    mask = pix.createMaskFromColor(QColor(255, 255, 255), Qt.MaskOutColor)

    p = QPainter(pix)
    p.setPen(QColor(0, 0, 255))
    p.drawPixmap(pix.rect(), mask, mask.rect())
    p.end()

Note that createMaskFromColor is going to convert the pixmap to a QImage, so you should try to use a QImage directly, if possible.

like image 105
Paolo Capriotti Avatar answered Sep 27 '22 22:09

Paolo Capriotti