我想使用 PIL 加载图像,应用一些过滤,然后在 GUI 上显示图像。
我写了一个小示例应用程序:
from PyQt4 import QtCore, QtGui
from PIL import Image, ImageQt
class TwoDToThreeD(QtGui.QWidget):
def __init__(self):
QtGui.QWidget.__init__(self)
layout = QtGui.QGridLayout()
self.btnOpen = self.createButton("Open File", self.open)
layout.addWidget(self.btnOpen, 4, 0)
self.imageLabel = QtGui.QLabel()
self.imageLabel.setBackgroundRole(QtGui.QPalette.Base)
self.imageLabel.setSizePolicy(QtGui.QSizePolicy.Ignored, QtGui.QSizePolicy.Ignored)
self.imageLabel.setScaledContents(True)
layout.addWidget(self.imageLabel, 0, 2, 4, 1)
layout.setColumnStretch(1, 10)
layout.setColumnStretch(2, 20)
self.setLayout(layout)
def createButton(self, text, member):
button = QtGui.QPushButton(text)
button.clicked.connect(member)
return button
def open(self):
fileName = (QtGui.QFileDialog.getOpenFileName(self, "Open File", QtCore.QDir.currentPath()))
if fileName:
print (fileName)
self.imgPil = Image.open(str(fileName))
# print (PIL.VERSION)
print (self.imgPil.format, self.imgPil.size, self.imgPil.mode)
# imgPil.show()
img_tmp = ImageQt.ImageQt(self.imgPil)
image = QtGui.QImage(img_tmp)
if image.isNull():
QtGui.QMessageBox.information(self, "Image Viewer", "Cannot load %s." % fileName)
return
self.imageLabel.setPixmap(QtGui.QPixmap.fromImage(image))
if __name__ == '__main__':
import sys
app = QtGui.QApplication(sys.argv)
dialog = TwoDToThreeD()
dialog.show()
sys.exit(app.exec_())
加载 *.png 工作正常。但是当我尝试加载 *.jpg python 时,它崩溃了:
python.exe has stopped working
A problem caused the program to stop working correctly.
Windows will close the program and notify you if a solution is
available.
我在 Windows 8.1 64 位上,并尝试了与 python 2.7 64 位、python 2.7 32 位和 python 3.4 64 位相同的源。
对于所有 3 个版本,我得到相同的结果。
有没有人遇到过类似的问题或知道解决方案?我什至无法调试代码,因为它一直运行到"结束"然后崩溃:(
在 PyQt5
和 Python 3.8 中,这不再有效。我会按如下方式编写pil2pixmap
函数。
import io
from PyQt5.QtGui import QImage, QPixmap
from PIL import Image
def pil2pixmap(image):
bytes_img = io.BytesIO()
image.save(bytes_img, format='JPEG')
qimg = QImage()
qimg.loadFromData(bytes_img.getvalue())
return QPixmap.fromImage(qimg)
其中参数image
例如image = Image.open('path_to_a_picture')
注意:要使用该功能,QGui应用程序必须运行
基于 github 的示例
def pil2pixmap(self,im):
if im.mode == "RGB":
pass
elif im.mode == "L":
im = im.convert("RGBA")
data = im.convert("RGBA").tostring("raw", "RGBA")
qim = QtGui.QImage(data, im.size[0], im.size[1], QtGui.QImage.Format_ARGB32)
pixmap = QtGui.QPixmap.fromImage(qim)
return pixmap
def open(self):
fileName = (QtGui.QFileDialog.getOpenFileName(self, "Open File", QtCore.QDir.currentPath()))
if fileName:
imgPil = Image.open(str(fileName))
# do your work then convert
self.imageLabel.setPixmap(self.pil2pixmap(imgPil))