5

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.]

Jeff
  • 968
  • 1
  • 10
  • 25

1 Answers1

10

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.

Paolo Capriotti
  • 4,052
  • 21
  • 25
  • I guess I'll accept this approach if there is no other. Is there really no way that a pixmap can iterate through its pixels, replacing ones of a certain color? Seems useful and simple to implement! – Jeff Dec 25 '11 at 10:52
  • Of course there is: you can convert it to a `QImage`, then use `bits` or `pixel` to access individual pixels. The approach with `createMaskFromColor` is going to be faster, I think, although probably not by much. – Paolo Capriotti Dec 25 '11 at 10:59
  • Hello, I know this is a old question (sorry for disturbing it) but did you have any luck with this? I am trying to do the same thing – joshua-anderson Sep 06 '13 at 01:40