如何将 QPixmap 的图像转换为字节

How to convert a QPixmap's image into a bytes

我想从 QLabel 中获取图像数据,然后将其存储到 PostgreSQL 数据库中,但我无法将其存储为 QPixmap,首先我需要将其转换为字节。这就是我想知道的。

我已经阅读了 pyqt5 文档的一部分,特别是 QImage 和 QPixmap 的部分,但还没有看到我要找的内容。

from PyQt5 import QtWidgets, QtGui
class Widget(QtWidgets.QWidget):
    def __init__(self):
        super().__init__(None)
        self.label = QtWidgets.QLabel(self)
        self.label.setPixmap(QtGui.QPixmap("ii_e_desu_ne.jpg"))
        self.setFixedSize(400,400)
        self.label.setFixedSize(200, 200)
        self.label.move(50, 50)
        self.show()

    #All is set now i want to convert the QPixmap instance's image 
    #into a byte string

app = QtWidgets.QApplication([])
ventana = Widget()
app.exec_()

如果要转换QPixmap to bytes you must use QByteArray and QBuffer:

# get QPixmap from QLabel
pixmap = self.label.pixmap()

# convert QPixmap to bytes
ba = QtCore.QByteArray()
buff = QtCore.QBuffer(ba)
buff.open(QtCore.QIODevice.WriteOnly) 
ok = pixmap.save(buff, "PNG")
assert ok
pixmap_bytes = ba.data()
print(type(pixmap_bytes))

# convert bytes to QPixmap
ba = QtCore.QByteArray(pixmap_bytes)
pixmap = QtGui.QPixmap()
ok = pixmap.loadFromData(ba, "PNG")
assert ok
print(type(pixmap))

self.label.setPixmap(pixmap)

QImage也一样,"PNG"是要转换的格式,因为QImage/QPixmap抽象了文件格式,可以使用here.[=16]指示的格​​式=]