Search code examples
qtbase64qstringqpixmap

How to convert QPixmap to base64 QString in Qt?


I am using QT 5.7 for a program where I have to convert a QPixmap to base64 QString format. I have tried to first convert the QPixmap to cv::Mat and then added my existing conversion flow.

Qpixmap pix;
cv::Mat pixData(pix.rows(),pix.cols(),CV_8UC3,pix.scanline());
                std::vector<uchar> IMbuffer;
                cv::imencode(".png", pixData, IMbuffer);
     QByteArray byteArray = QByteArray::fromRawData((const char*)IMbuffer.data(), IMbuffer.size());
                QString base64Image(byteArray.toBase64());

But it returns error:

error: 'class QPixmap' has no member named 'rows'
    cv::Mat pixData(pix.rows(),pix.cols(),CV_8UC3,pix.scanline());
                    ^

So it is clear that such conversion from QPixmap to cv::Mat is incompatible. So is there any easy way to convert QPixmap to base64 QString?


Solution

  • Try this;

     QBuffer buffer;
     buffer.open(QIODevice::WriteOnly);
     pix.save(&buffer, "PNG");
     auto const encoded = buffer.data().toBase64();