RodericDay
RodericDay

Reputation: 1292

Better way of going from PIL to PySide QImage?

My app loads up an image and prints some text onto it. Then I want to use the printed image as a label on a button's icon.

The problem is that I can't pass an "Image" onto QIcon or any PyQt class. I found a method online that recommended sending the file as a raw string into Qt's parser, and reconstructing the image from that.

It worked really well, except that the image was blue. After reading up a bit on image processing I learned that to fix it I need to shift and reverse all the bits, so

        data = im.convert('RGBA').tostring()
    data = ''.join([''.join(i) for i in zip(data[2::4],data[1::4],data[0::4],data[3::4])])
    qim = QtGui.QImage(data, im.size[0], im.size[1],
                    QtGui.QImage.Format_ARGB32)
    pix = QtGui.QPixmap.fromImage(qim)

my little join/zip magic there seems somewhat out of place, and I don't understand why it is necessary. Is there a better way to do this? I know there is a blatant issue in spitting out RGBA and parsing it as ARGB, but I explored PIL and PyQt docs to no avail.

Upvotes: 4

Views: 1907

Answers (1)

mata
mata

Reputation: 69022

PIL (1.6 and later) has a module ImageQt, which makes it very easy to convert an Image to a QImage, at least for PyQt4. If you need it to work with PySide also, it should be a simple change to the source

Upvotes: 7

Related Questions