问题描述
我正在尝试编写一个小型图形应用程序,我需要
使用我在小部件中显示的PIL构建一些图像。
图像构造正确(我可以用im.show()查询),
我可以将它转换为QImage,我可以正常保存到磁盘
(使用QImage.save) ,但是如果我尝试直接在我的
QWidget上绘制它,它只显示一个白色方块。
I'm trying to write a small graphic application, and I need toconstruct some image using PIL that I show in a widget.The image is correctly constructed (I can check with im.show()),I can convert it to a QImage, that I can save normally to disk(using QImage.save), but if I try to draw it directly on myQWidget, it only show a white square.
这里我注释掉了无效的代码(将
图像转换为QImage,然后将QPixmap转换为白色方块),并且我
做了一个脏的黑客将图像保存到临时文件并直接加载到QPixmap中的
,这工作正常但不是我想做的事情
Here I commented out the code that is not working (converting theImage into QImage then QPixmap result in a white square), and Imade a dirty hack to save the image to a temporary file and load it directlyin a QPixmap, which work but is not what I want to do
有人知道吗?
如果可以的话帮助,当我尝试将我的QImage保存在BMP文件中时,我可以访问其内容,但如果我尝试将其保存到PNG,则它是完全白色的
If it can help, when I try to save my QImage in a BMP file, I can access its content, but if I try to save it to a PNG it is completely white
推荐答案
有同样的问题,然后注意到,ImageQt对象不是QImages,但可以简单地转换为那些
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_())
这篇关于使用PIL和PyQt在小部件上绘制QImage时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!