Qt 6.11 is out! See what's new in the release
blog
QImage from JSON double encoded data
-
Hi,
I'm receiving an image through JSON.
I cannot share file data due char limitation. Please download it on WeTransfer:
It seems that the image has been double encoded: "Windows-1252" -> "UTF-8" -> "base64".
How do I revert the double encoding?
QFile qFile("image.json"); if (qFile.open(QIODeviceBase::ReadOnly)) { QTextStream qStream(&qFile); QByteArray qBuffer = qStream.readAll().toUtf8(); QJsonParseError* pqError = nullptr; QJsonDocument qJsonDoc = QJsonDocument::fromJson(qBuffer, pqError); if (!qJsonDoc.isNull()) { QJsonObject qJsonObject = qJsonDoc.object(); if (qJsonObject.contains("IMG")) { QString base64 = qJsonObject.value("IMG").toString(); //Here I need to do the double decoding QImage qImage; } } }Regards,
-
-
Hi,
Finally I found a solution. It seems that the error starts with the data extracted from a Database that is bad encoded. The solution:
QString qImgB64 = qJsonObject.value("IMG").toString(); // Base64 → "corrupted bytes" QByteArray qDecoded = QByteArray::fromBase64(qImgB64.toLatin1()); // UTF-8 QString utf8Text = QStringDecoder(QStringDecoder::Utf8)(qDecoded); // Convert to CP1252 QStringEncoder encoder(QStringEncoder::System); // or Windows-1252 "QStringEncoder encoder("Windows-1252");" QByteArray qJpeg = encoder(utf8Text); // Load into image QImage qImage; bool ok = qImage.loadFromData(qJpeg);Thanks
-
O ollarch has marked this topic as solved