Bug when drawing a QImage on a widget with PIL and PyQt

前端 未结 2 1805
悲&欢浪女
悲&欢浪女 2020-12-11 11:40

I\'m trying to write a small graphic application, and I need to construct some image using PIL that I show in a widget. The image is correctly constructed (I can check with

相关标签:
2条回答
  • 2020-12-11 11:58

    Had the same problem, then noticed, that ImageQt objects are not QImages, but can simply be casted to those

    #!/usr/bin/python
    # -*- coding: utf-8 -*-
    #written by Sebastian Stetter in 2010
    
    
    import sys
    from PIL import Image
    from PIL.ImageQt import ImageQt
    
    from PyQt4.QtGui import *
    from PyQt4.QtCore import *
    
    
    
    def PILimageToQImage(pilimage):
        """converts a PIL image to QImage"""
        imageq = ImageQt(pilimage) #convert PIL image to a PIL.ImageQt object
        qimage = QImage(imageq) #cast PIL.ImageQt object to QImage object -that´s the trick!!!
        return qimage
    
    
    
    
    if __name__ == "__main__":
        #Testcode
        app = QApplication(sys.argv)
    
        pim = Image.open(unicode(QFileDialog().getOpenFileName()))
        pim.show() #show pil image
    
        qim = PILimageToQImage(pim)
        pm = QPixmap(qim)
        lbl = QLabel()
        lbl.setPixmap(pm)
        lbl.show() #show label with qim image
    
        sys.exit(app.exec_())
    
    0 讨论(0)
  • 2020-12-11 12:16

    I've done the same thing with Qt-3 using QImage.loadFromData(). I imagine it still works in Qt-4:

    self.image = QImage()
    if self.image.loadFromData(image_data,"PNG"):
        # image loaded successfully
    
    0 讨论(0)
提交回复
热议问题