Home > Mobile >  How Can Pass QImage to qml without ImageProvider?
How Can Pass QImage to qml without ImageProvider?

Time:04-17

I use this link to read an image from SQL dataBase (the image saved in dataBase as BLOB) and pass it to qml but I get this error : QML Image: Error decoding: data:image/png;base64,77 9UE5HDQoaCg==: Unsupported image format

how can I fix this error?

cpp:

void MainWindow::saveToDatabase(QQuickItem *imageObj) {

  QSharedPointer<const QQuickItemGrabResult> grabResult =
      imageObj->grabToImage();
  connect(grabResult.data(), &QQuickItemGrabResult::ready, [=]() {
    QImage img(grabResult->image());
    QByteArray imageArray;
    QBuffer buffer(&imageArray);
    buffer.open(QIODevice::WriteOnly);
    img.save(&buffer, "PNG");
    dbModify->dbinsertRecords(imageArray);
  });
}


QString MainWindow::convertToImage(int pos) {
       //SelectLastData define as QVariantList in header
        QString base64 =
            QString::fromUtf8(SelectLastData[pos].toByteArray().toBase64().data());
        return QString("data:image/png;base64,")   base64;
    }

qml:

onClicked: {
     stackView.push("qrc:/imagePage.qml",  {"url" : mainWindow.convertToImage(9)})
           }

imagePage.qml:

Page {
    width: Screen.width
    height: Screen.height
    visible: true
    property alias url: screenshoot.source
    Rectangle {
  Image {
         id: screenshoot
       }
    }
}

CodePudding user response:

The base64 data in the error message: "77 9UE5HDQoaCg==" corresponds to the bytes ef bf bd 50 4e 47 0d 0a 1a 0a which includes 3 bytes that shouldn't be there for a PNG header (it should start with 89 50 4e 47) and that indicates that the data is truncated, which means the data is read as a null terminated string instead of a binary blob (9th byte of a PNG file is usually a null character).

That is probably because you are passing a char* to QVariant instead of a QByteArray when you initialize the QVariantList.

Basically, when you pass a char* as a parameter to its constructor or setValue, QVariant interprets it as a null terminated UTF-8 string and stores it natively as a QString, then, when you call toByteArray it converts it to UTF-8. The 2 conversions from and to UTF-8 can cause corruption on binary data.

If you create an intermediate QByteArray variable and use it directly to initialize the QVariant, it will be stored as QByteArray and no conversion will occur when you'll call toByteArray.

  • Related