Snippet. CPP. QIcon to Base64 encoded QString

This CPP snippet will convert a QIcon to Base64 QString.

QString base64_encode_icon(QIcon icon, int width, int height){
    QImage image(icon.pixmap(width, height).toImage()); // 20,20 are the size of the icon
    QByteArray byteArray;
    QBuffer buffer(&byteArray);
    image.save(&buffer, "PNG"); // writes the image in PNG format inside the buffer
    QString iconBase64 = QString::fromLatin1(byteArray.toBase64().data());
    return iconBase64;
}

Example

// Retrieve icon from resources
QIcon icon(":/resource/images/note_22_22.png");

// Display the Base64 converted QString
qDebug() << base64_encode_icon(icon, 22, 22);

Updated on: 26 Apr 2024