Qt World Summit: Submit your Presentation

Transferring an image from server to client (raw data of a QImage ?)

  • Hi all!

    I'm trying to send an image from a server to a client through a QJsonObject.

    I figured out a way to create again the image (client-side) with this method:

    QImage(uchar *data, int width, int height, QImage::Format format,)

    But on the server side, I can't get how to extract the raw data of a QImage.
    How to use the method bits() ? How to encapsulate these bits in a QJsonObject ?

    Thank you for your help!

  • Moderators

    @duarna said in Transferring an image from server to client (raw data of a QImage ?):

    How to use the method bits()

    better use constBits(). It returns the bytes of the raw image data.
    Use the bytesPerLine() / width() / height() or sizeInBytes() methods in a for-loop and store it in a QByteArray.

    To store the data in a JSON format you should convert the QByteArray to a base64 string.

  • Thank you @raven-worx for your quick reply.

    I'm sorry but can you provide me a short example on how to fulfil a QByteArray with uchar* and how to get back the uchar* from it ?
    I'm lost

    Thank you

  • Moderators

    This will create a QByteArray which is valid as long as also the QImage data is valid. If QImage gets deleted and you still try to use the QByteArray afterwards it will crash. But the benefit of this is it is faster of course.

    QByteArray data = QByteArray::fromRawData((const char*)image.constBits(), image.byteCount());

    Alternatice to make a deep copy of the data you can use the QByteArray constructor:

    QByteArray data = QByteArray((const char*)image.constBits(), image.byteCount());

  • Ok got it, thank you for your help.
    here is my updated solution, because you were using old-style cast and obsolete method:

    On server side:

    QImage img("pathToImage"); 
    QByteArray data = QByteArray::fromRawData(reinterpret_cast<const char*>(img.constBits()), static_cast<int>(img.sizeInBytes()));
    QString strContent = data.toBase64(); //convert to a mqtt-compliant string

    And on the client side, assuming that the data of the image comes with the value "data":

    QString strContentB64 = p_image.value("data").toString(""); //get the raw string
    QByteArray baContentB64; baContentB64.append(strContentB64); //convert to QByteArray
    QByteArray baContent = QByteArray::fromBase64(baContentB64); //convert from Base64
    QImage img = QImage(reinterpret_cast<const uchar*>(baContent.constData()), width, height, static_cast<QImage::Format>(format));

    Again, thanks a lot!

Log in to reply