How to get a picture from QString in Qt
-
@mikeeeeee Hi,
I think it's easier if you use
QDataStream
.
I never tested but it seems quite straightforwardWrite
QDataStream out(&socket); // serialize the data out << myImage; // serialize an image
Read
QDataStream in(&socket); // read the data serialized from the socket QImage myImage; in >> myImage; // extract image
-
@mikeeeeee said in How to get a picture from QString in Qt:
I use TcpSocket
Then you don't need
QString
. You needQByteArray
, probablyQDataStream
as @Gojir4 pointed out.QString imageString = QString::fromStdString(bArray.toStdString());
Sorry, but never do that!
QString imageString = QString::fromUtf8(bArray);
is most often correct, sometimesfromLatin1()
orfromLocal8Bit()
might be needed too.But as said, your problem cannot be solved with QString.
Regards
-
Hi,
As already explained by my fellows, use QByteArray. QString is for string manipulation, it's not what you are doing. You are sending data through network. Therefore you are creating a base64 QByteArray that represent your image's binary data. There's no need for any QString in between.
-
But as I write in Qbytearray json?
And why this doesn't it work:/*QString imageString = QString::fromLocal8Bit(bArray); bArray2 = QByteArray::fromHex(imageString.toLocal8Bit());*/ QString imageString = QString::fromLatin1(bArray); bArray2 = QByteArray::fromHex(imageString.toLatin1()); if (bArray != bArray2) {qDebug()<<"bArray != bArray2";} else {"bArray == bArray2";}
debug return: bArray != bArray2
-
At one point you are encoding in base64 and the other you are decoding from hex. These are two completely different things.
Also, QString does a conversion to UTF16. So again, the fact that JSON contains text doesn't mean that you need to use QString.
-
Take a look at QJsonDocument, no QString there.
-
You have to understand that it's the QByteArray that will contain the JSON data.
Again, read the documentation of QJsonDocument, the related classes and example code.
-
@mikeeeeee Then you need to read more carefully.
https://doc.qt.io/qt-5/qjsondocument.html#toJson
https://doc.qt.io/qt-5/qjsondocument.html#fromJson -
@mikeeeeee do you actually want a qbytearray as a value to a key inside your son file ?
-
So it turns QString into a picture to translate
QString AppCore::getImage(QString addressFile) { QImage myImage(addressFile); QByteArray bArray; QBuffer buffer(&bArray); buffer.open(QIODevice::WriteOnly); myImage.save(&buffer, "JPEG"); QString image("data:image/jpg;base64,"); image.append(QString::fromLatin1(bArray.toBase64().data())); QImage testImage(image); qDebug()<<"myImage.size() : "<<myImage.size(); return image; }