[SOLVED] Pyside, Pil image to QPixmap



  • For a few days now I've been trying to format a simple rgba pil image into a pixmap.
    So as to display it using a painter, I.E:

    @
    self.image = converted pil to pixmap

    this = QtGui.QPainter(self)
    this.drawPixmap( self.rect(), self.image )
    @

    My knowledge so far leads me to implement this conversion method:
    @
    data = self.image.tostring('raw', 'RGBA')
    image = QtGui.QImage.fromData(data)
    data = None
    pixmap = QtGui.QPixmap.fromImage(image)
    image = None
    return pixmap
    @

    However, when painting, nothing appears.
    When investigating further I noticed that the pixmap dimensions were (0,0)

    So somewhere I may be loosing some formatting?
    Or I am missing an image parameter for either a QPixmap or QImage..

    Any thoughts?



  • QImage is not able to parse the current data returned to pil image you need to inform more details to make this possible, you can use that code to create a QImage fom the pil data.

    @from PIL import Image
    from PySide.QtGui import QImage, QImageReader, QLabel, QPixmap, QApplication

    im = Image.open("my_image.png")
    data = im.tostring('raw', 'RGBA')

    app = QApplication([])

    image = QImage(data, im.size[0], im.size[1], QImage.Format_ARGB32)
    pix = QPixmap.fromImage(image)
    lbl = QLabel()
    lbl.setPixmap(pix)
    lbl.show()

    app.exec_()@



  • I noticed that both our renditions work, the version of pyside I am running has a bug in QImage(str ...

    just found out

    Fedora 14 doesn't have 1.0.2, which fixed that issue.
    The current windows version seems to work fine.

    Though, I might of found a new bug in QPainter.drawImage()
    Which crashes python under windows 7



  • The reason why it probably crashes on Windows 7, is that the Python interpreter loses the reference to image data, and frees the memory.

    For instance, in "PIL ImageQt.py":http://www.java2s.com/Open-Source/Python/GUI/Python-Image-Library/Imaging-1.1.7/PIL/ImageQt.py.htm the image data reference is separately stored into a class member variable:

    @
    # must keep a reference, or Qt will crash!
    self.__data = data or im.tostring()
    @

    Once I did this in my conversion function/class, the conversion method works flawlessly on Windows 7. The reason why QPixmap doesn't save the data reference correctly to prevent automatic garbage collection (I guess) is a bit beyond me.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.