May 12, 2011

Raschko Raschko
Lab Rat
10 posts

[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:

  1. self.image = converted pil to pixmap
  2.  
  3. this = QtGui.QPainter(self)
  4. this.drawPixmap( self.rect(), self.image )

My knowledge so far leads me to implement this conversion method:

  1. data = self.image.tostring('raw', 'RGBA')
  2. image = QtGui.QImage.fromData(data)
  3. data = None
  4. pixmap = QtGui.QPixmap.fromImage(image)
  5. image = None
  6. 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?

 Signature 

Shop smart, shop “S"mart!

3 replies

May 12, 2011

renato.filho renato.filho
Hobby Entomologist
52 posts

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.

  1. from PIL import Image
  2.  
  3. im = Image.open("my_image.png")
  4. data = im.tostring('raw', 'RGBA')
  5.  
  6. app = QApplication([])
  7.  
  8. image = QImage(data, im.size[0], im.size[1], QImage.Format_ARGB32)
  9. pix = QPixmap.fromImage(image)
  10. lbl = QLabel()
  11. lbl.setPixmap(pix)
  12. lbl.show()
  13.  
  14. app.exec_()

May 14, 2011

Raschko Raschko
Lab Rat
10 posts

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

 Signature 

Shop smart, shop “S"mart!

July 29, 2011

jusic jusic
Lab Rat
1 posts

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 [java2s.com] the image data reference is separately stored into a class member variable:

  1.         # must keep a reference, or Qt will crash!
  2.         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.

 
  ‹‹ PySide: QtSingleApplication?      PySide: translate() String with variable arguments ››

You must log in to post a reply. Not a member yet? Register here!