[PyKDE] PyQt4: Problems with QImage.loadFromData(data)
Stephan Heuel
stephan at heuel.org
Tue Mar 14 15:41:43 GMT 2006
Dear all
I have now a working example, the main point is to correctly convert
the string to PIL and import it into PyQt:
s = im.convert("RGB").tostring("jpeg","RGB")
image.loadFromData(QtCore.QByteArray(s))
A complete working example is attached below.
Cheers
Stephan
--------------------------------------------
# How to use PIL images in PyQt4
#
# PIL: http://www.pythonware.com/products/pil/
# PyQt4: http://www.riverbankcomputing.com/Downloads/Snapshots/PyQt4/
# 14.03.2006 - 16:40
import os, sys
import Image
from PyQt4 import QtCore, QtGui
class MiniViewer(QtGui.QWidget):
"this class demonstrates how to use PIL images in PyQt [does not work yet!]"
def __init__(self, parent = None):
QtGui.QWidget.__init__(self, parent)
# initialize QImage
self.image = QtGui.QImage()
def open(self,infile):
# load an image using PIL, first read it
self.PILimage = Image.open(infile)
# now update the QImage according to the PIL image
self.__PIL2Qt()
def __PIL2Qt(self, encoder="jpeg", mode="RGB"):
# I have only tested the jpeg encoder, there are others, see
# http://mail.python.org/pipermail/image-sig/2004-September/002908.html
PILstring = self.PILimage.convert(mode).tostring(encoder, mode)
self.image.loadFromData(QtCore.QByteArray(PILstring))
def paintEvent(self, Event):
painter = QtGui.QPainter(self)
painter.drawImage(0,0,self.image)
def perspectiveTransform(self):
# this is just an example to demonstrate that one can do
# perspective transformations with PIL (something not
# supported with Qt, it "only" can do affine transformations).
size = self.PILimage.size
self.PILimage = self.PILimage.transform(size,
Image.PERSPECTIVE,
[2,0,0,0,2,0,0.002,0.002,1],Image.BILINEAR)
self.__PIL2Qt()
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
viewer = MiniViewer()
# load your own file, do a PIL transformation and show it off!
viewer.open("D:/Data/Images/mit.png")
viewer.perspectiveTransform()
viewer.show()
sys.exit(app.exec_())
More information about the PyQt
mailing list