如何在pyqt中显示RGB图像

How to display RGB image in pyqt

我在 RBG 模式下有一张图片,当我尝试在 qdockWidget 上显示它时,图片显示不正确。我可以在 "L" 模式下打印图像。我错过了什么。提前致谢:)

代码如下:

from PyQt5 import QtWidgets, QtGui
from PyQt5.QtWidgets import (QApplication, QMainWindow)
from PyQt5.QtCore import Qt

from reportlab.graphics.shapes import *

from PIL import ImageQt
from PIL import Image, ImageDraw


class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.resize(800, 600)

        dockWidget = QtWidgets.QDockWidget()
        dockWidget.setWindowTitle("Image Viewer")

        w, h = 220, 190
        shape = [(40, 40), (w - 10, h - 10)]

        # creating new Image object
        img = Image.new("RGB", (w, h))

        # create rectangleimage
        img1 = ImageDraw.Draw(img)
        img1.rectangle(shape, fill="#800080", outline="green")
        img.show()

        QtImage1 = ImageQt.ImageQt(img)
        QtImage2 = QtGui.QImage(QtImage1)
        pixmap = QtGui.QPixmap.fromImage(QtImage2)
        label = QtWidgets.QLabel('testing', self)
        label.setPixmap(pixmap)

        dockWidget.setWidget(label)
        dockWidget.setFloating(False)
        self.addDockWidget(Qt.RightDockWidgetArea, dockWidget)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    myWidget = MainWindow()
    myWidget.show()

    sys.exit(app.exec_())

问题是"img"和"QtImage1"、"QtImage2"和"pixmap"共享同一个缓冲区导致错误,解决办法是复制图片:

qimage = ImageQt.ImageQt(img)<b>.copy()</b>
pixmap = QtGui.QPixmap.fromImage(qimage)
label = QtWidgets.QLabel()
label.setPixmap(pixmap)