Simple situation: I have an object, which has a QPixmap
member. Object first created (pixmap is null now), then pixmap readed from data base and inserted in obj
This is my two cents about serializing/deserializing QPixmap to/from Base64 e strings. I've included methods to load/save the image as a text file but also two simple toBase64()
and fromBase64()
that help with HTML, SQL or JSON encoding.
#include "b64utils.h"
#include
#include
#include
/**
* Serializes a QPixmap object into a Base64 string
*/
QString B64Utils::toBase64(QPixmap *pixmap) {
// Convert the pixel map into a base64 byte array
QBuffer *buffer = new QBuffer;
pixmap->save(buffer, "png");
QByteArray b64 = buffer->data().toBase64();
QString *b64Str = new QString(b64);
return *b64Str;
}
/**
* Serializes a QPixmap object into a Base64 string and save it to a file
*/
bool B64Utils::savePixmapToBase64(QPixmap *pixmap, QString filePath) {
// Opens a file for writing text
QFile file(filePath);
if (!file.open(QIODevice::WriteOnly | QFile::Text)) return false;
// Write the Base64 string into the file
QTextStream stream(&file);
stream << toBase64(pixmap);
file.close();
return true;
}
/**
* Deserializes a Base64 string, representing an image, into a QPixmap
*/
QPixmap* B64Utils::fromBase64(QString b64Str) {
QPixmap *pixmap = new QPixmap;
pixmap->loadFromData(QByteArray::fromBase64(b64Str.toUtf8()));
return pixmap;
}
/**
* Retrieves a Base64 string, representing an image, from a file and deserializes it into a QPixmap
*/
QPixmap* B64Utils::loadPixmapFromBase64(QString filePath) {
// Opens a file for reading text
QFile file(filePath);
if (!file.open(QFile::ReadOnly | QFile::Text)) return nullptr;
// Reads the contents of the file into a string
QTextStream in(&file);
QString b64Str = in.readAll();
file.close();
return fromBase64(b64Str);
}