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

4

我想从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_()

转换QPixmapnumpy.ndarray此答案应该有效。只需省略将数据从字节字符串转换为numpy数组的最后一步即可。 - CodeSurgeon
1个回答

8
如果你想将 QPixmap 转换为字节,你必须使用 QByteArrayQBuffer
# 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抽象了文件格式,您可以使用此处指定的格式

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接