Problems with Open-Source Downloads read https://www.qt.io/blog/problem-with-open-source-downloads and https://forum.qt.io/post/638946

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.

    cv::Mat pixData(pix.rows(),pix.cols(),CV_8UC3,pix.scanline());
                std::vector<uchar> IMbuffer;
              //  std::vector<uint8_t> 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?


  • Lifetime Qt Champion

    Hi,

    QPixmap::size is likely what you are looking for.

    But there's no need to have OpenCV involved. Take a look at QPixmap::save



  • @SGaist
    I have tried from here

    QPixmap pix;
    QImage image = pix.toImage();
     QByteArray byteArray;
    
     QBuffer buffer(&byteArray);
    
        image.save(&buffer, "JPEG"); // writes the image in JPEG format inside the buffer
    
        QString iconBase64 = QString::fromLatin1(byteArray.toBase64().data());
    

    But it returns:

     error: 'QBuffer' was not declared in this scope
                QBuffer buff(&byteArray);
                ^
    

  • Moderators

    @sigmind said in How to convert QPixmap to base64 QString in Qt?:

     error: 'QBuffer' was not declared in this scope
                QBuffer buff(&byteArray);
                ^
    

    Your compiler is telling you that you need to #include the QBuffer header.

    QPixmap pix;
    QImage image = pix.toImage();
    QByteArray byteArray;
    QBuffer buffer(&byteArray);
    

    Why not use @SGaist's suggestion? QPixmap::save()


Log in to reply