I am using Qt on Windows and I want to turn this part here:
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADIA..." />
into the native binary encoding of a .png file. I have already isolated the iVBORw0KGgoAAAANSUhEUgAAADIA... part as a QString, my only question is how to convert that into say, a QByteArray that can be written to a file. Specifically, a .png file. The QByteArray::fromBase64 method is what I tried, it doesn't work.
So my code is:
QDataStream stream(&file);
QByteArray qba;
qba.append(sourcestring);
stream << QByteArray::fromBase64(qba);
sourcestring is the source string (with the data:image/png;base64, part removed) and file is the png file I am writing to.
You might do this:
QString s("iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAl...");
QByteArray ba = QByteArray::fromBase64(s.toUtf8());
QImage img = QImage::fromData(ba);
img.save("test.png");
Related
Hi im new to Qt and im trying to read for example the first 4 bytes of my .txt file and show it. I've been searching and figure that QbyteArray may help me best in this situation. so I really like to know how can i read the first 4 bytes of my file with QbyteArray? (appreciate if u write any example code)
Assuming your code contains something like this:
QFile file{ "path/to/file.txt" };
You can read a number of bytes from a file with file.read(n), assuming n to be a number of bytes. you can also use file.readAll() to get the entire thing
for more advanced input/output operations, you can use the QTextStream class as such:
QFile file { "path/to/file.txt" };
QTextStream stream { &file };
(This is a stream that can read and write data to the provided device, here, a file.)
For more info, see here:
https://doc.qt.io/qt-6/qfile.html for QFile
https://doc.qt.io/qt-6/qtextstream.html for QTextStream
So I have a QT text editor that I have started creating. I started with this http://doc.qt.io/archives/qt-5.7/gettingstartedqt.html and i have added on to it. So far I have added a proper save/save as function (the version in the link only really has a save as function), a "find" function, and an "open new window" function. Very soon, I will add a find and replace function.
I am mainly doing this for the learning experience, but I am also going to eventually add a few more functions that will specifically help me create PLC configuration files at work. These configuration files could be in many different encodings, but most of them seem to be in UTF-16LE (according to Emacs anyway.) My text editor originally had no problem reading the UTF-16LE, but wrote in plain text, I needed to change that.
Here is the snippet from the Emacs description of the encoding system of one of these UTF16-LE files.
U -- utf-16le-with-signature-dos (alias: utf-16-le-dos)
UTF-16 (little endian, with signature (BOM)).
Type: utf-16
EOL type: CRLF
This coding system encodes the following charsets:
unicode
And here is an example of the code that I am using to encode the text in my QT text editor.
First... This is similar to the link that I gave earlier. The only difference here is that "saveFile" is a global variable that I created to perform a simple "Save" function instead of a "Save As" function. This saves the text as plain text and works like a charm.
void findreplace::on_actionSave_triggered()
{
if (!saveFile.isEmpty())
{
QFile file(saveFile);
if (!file.open(QIODevice::WriteOnly))
{
// error message
}
else
{
QTextStream stream(&file);
stream << ui->textEdit->toPlainText();
stream.flush();
file.close();
}
}
}
Below is my newer version which attempts to save the code in "UTF-16LE." My text editor can read the text just fine after saving it with this, but Emacs will not read it at all. This to me says that the configuration file will probably not be readable by the programs that read it. Something changed, not sure what.
void findreplace::on_actionSave_triggered()
{
if (!saveFile.isEmpty())
{
QFile file(saveFile);
if (!file.open(QIODevice::WriteOnly))
{
// error message
}
else
{
QTextStream stream(&file);
stream << ui->textEdit->toPlainText();
stream.setCodec("UTF-16LE");
QString stream3 = stream.readAll();
//QString stream2 = stream3.setUnicode();
//QTextCodec *codec = QTextCodec::codecForName("UTF-16LE");
//QByteArray stream2 = codec->fromUnicode(stream3);
//file.write(stream3);
stream.flush();
file.close();
}
}
}
The parts that are commented out I also tried, but they ended up writing the file as Asian (Chinese or Japanese) characters. Like I said my text editor, (and Notepad in Wine) can read the file just fine, but Emacs now describes the encoding as the following after saving.
= -- no-conversion (alias: binary)
Do no conversion.
When you visit a file with this coding, the file is read into a
unibyte buffer as is, thus each byte of a file is treated as a
character.
Type: raw-text (text with random binary characters)
EOL type: LF
This indicates to me that something is not right in the file. Eventually this text editor will be used to create multiple text files at once and modify their contents via user input. It would be great if I could get this encoding right.
Thanks to the kind fellows that commented on my post here, I was able to answer my own question. This code here solved my problem.
void findreplace::on_actionSave_triggered()
{
if (!saveFile.isEmpty())
{
QFile file(saveFile);
if (!file.open(QIODevice::WriteOnly))
{
// error message
}
else
{
QTextStream stream(&file);
stream.setCodec("UTF-16LE");
stream.setGenerateByteOrderMark(true);
stream << ui->textEdit->toPlainText();
stream.flush();
file.close();
}
}
}
I set the codec of the stream, and then set the the generate BOM to "True." I guess that I have more to learn about encodings. I thought that the byte order mark had to be set to a specific value or something.I wasn't aware that I just had to set this value to "True" and that it would take care of itself. Emacs can now read the files that are generated by saving a document with this code, and the encoding documentation from Emacs is the same. I will eventually add options for the user to pick which encoding they need while saving. Glad that I was able to learn something here.
Using QByteArray QIODevice::readAll() from QT5, I was able to make a bytes array from a txt file or an image, used decode after and recreated the file correctly. But, when I tried with a .db file (SQLITE) it didn't work.
I noticed that when you open a .db with a text editor, you will see "SQLite format 3" followed by encoded characters. After making a QByteArray from a .db file, followed by decode() to recreate the file, when I opened it with a text editor, the file only contains the text "SQLite format 3".
Does QByteArray only work with txt file or Image file?
If it does, how can I make a Array of bytes from a .db (SQLITE) file.
Thanks
Update1 (The code belows works):
QFile file("C:/database.db");
if(!file.open(QIODevice::ReadOnly))
qDebug()<<"You are stupid!";
QByteArray byteArray = file.readAll();
QFile file2("C:/database2.db");
file2.open(QIODevice::WriteOnly);
file2.write(byteArray);
file2.close();
file.close();
Update2:
About the decode I mentioned in my initial question, I was using the following:
QString QFile::decodeName(const QByteArray & localFileName)
which make no sense when you read carefully the documentation and was just wrong. :)
You should not open that file with QIODevice::Text flag.
Check this http://doc.qt.io/qt-5/qiodevice.html#OpenModeFlag-enum
I'm trying to compress a text file with QT:
QFile inFile("d:\\build\\Directories\\Debug\\files\\developer.txt");
bool open_file_result = inFile.open(QIODevice::ReadOnly);
QByteArray ba = inFile.readAll();
QFile file("d:\\build\\Directories\\Debug\\files\\developer.gz");
bool open_zip_result = file.open(QIODevice::WriteOnly);
QDataStream out(&file);
out << qCompress(ba);
file.close();
open_file_result and open_zip_result are both true. I can also see the zip file (it also has a size, such as 50KB) but I can't open it. I'm getting the following error:
The archive is either in unknown format or damaged.
What am I doing wrong? If you have a better/another way to compress a text file, please tell me!
There is a difference between the Zip compression algorithm and the Zip container. You're confusing the two.
You need to do some research into the Zip container format that will help you locate and extract a zipped file within a Zip container. Once you've gotten that file, you can apply qUncompress to that file only.
Try looking at the QuaZip, which is a library that has been written for this purpose.
Im using qt 5.0 and its support such classes as QJsonObject QJsonDocument and QJsonArray. In my programm i need to serialize json array and convert it to qstring/qbytearray but i didn't found any serialize or encode methods in those classes. Is there any way i can serialize data using included qt 5.0. libs? I found this example:
QVariant id(1), name("John Doe");
QJsonObject json;
json["Name"] = name.toString();
json.insert("id", id.toInt());
But i can't find how i can make an array from it.
Question closed. Use QJsonDocument::toJson to get data from QJsonObject.
I think the secret is that when serializing to JSON, Qt writes out a UTF-8 binary encoded version of the text into a QByteArray. You can recover the string using QString::fromUtf8. Also, even though toJson writes out a QByteArray it is not a true binary representation; as I just mentioned, it is the bytes of the UTF-8 encoded string representation of the JSON. For binary serialization you must use either Qt's own QJsonDocument::toBinaryData or find a BSON library.
Text serialization
Use QJsonDocument::toJson to serialize as text via a QString, and QJsonDocument::fromJson to deserialize from text.
Tip: Consider passing the QJsonDocument::Compact format option to get compact JSON output during serialization.
To QString
QString json = QString::fromUtf8(doc.toJson(QJsonDocument::Compact));
From QString
QJsonDocument doc = QJsonDocument::fromJson(json);
Binary serialization
Use QJsonDocument::toBinaryData to serialize as binary via a QByteArray, and QJsonDocument::fromBinaryData to deserialize from binary.
Caveat: The binary format used by the above functions is Qt's own binary format (qbjs) so may not be suitable for interoperation with other binary formats such as BSON. For that, you might want to look into choosing a BSON implementation.
To QByteArray
QByteArray bytes = doc.toBinaryData();
From QByteArray
QJsonDocument doc = QJsonDocument::fromBinaryData(bytes);