Search code examples
pythonpyqtpyqt5qimageqpixmap

How to convert a QPixmap's image into a bytes


I want to take an image's data from a QLabel and then store it into a PostgreSQL Database, but I cannot store it as QPixmap, first I need to convert it into a bytes. That's what I want to know.

I've read part of the pyqt5's doc, specially the QImage and QPixmap's section but haven't seen what I am looking for.

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_()

Solution

  • If you want to convert 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)
    

    The same is done with QImage, the "PNG" is the format to be converted since QImage/QPixmap abstracts the file format, you can use the formats indicated here.