Important: Please read the Qt Code of Conduct -

Converting QString to QByteArray using toUtf8() resulting in QByteArray with extra characters

  • I need this to store image in string format and then read the string, convert this string to Qbytearray and load the image back.

    void WorkWithImagesForSerialization_1()
        QImage original_image("someicon.png");
        if (original_image.isNull() != true)
            QByteArray original_bytearray;
            QBuffer original_buffer(&original_bytearray);
  , "png"); // writes image into ba in PNG format
            QString original_string;
            // PMJ : I did this because, constructing QString from byte arry would stop after finding first terminating character
            for (int i=0;i<original_bytearray.size();++i)
                original_string[i] = original_bytearray[i];
            QByteArray second_bytearray = original_string.toUtf8();
            // original_string =  "\211PNG\r\n\032\n\0.....
            // second_bytearray = "Â\211PNG\r\n\032\n\0....
            // Since, image is loaded from byte array, below image second_image is null.
            QImage second_image;
            // second_image is null here

    I expect QByteArray conversion should be proper so that I can reload the image.

  • Lifetime Qt Champion

    @Joshi Why do you need to convert an image to a string? What is the point of doing so? An image will contain any bytes and if you interpret them as UTF8 (!) you will get something like what you get (you can't expect resulting string to be readable).
    Strings are designed to store strings not arbitrary binary data.

  • as jlsum mentioned, using QString for storage of binary data is not optimal. In fact I'd stay away from it unless you are doing something like base64 encoding, which is human readable form for binary data used in email attachments and such. There are Qt classes specifically for object serialization. Id suggest researching them instead of shoehorning your binary image data into a QString.

  • Lifetime Qt Champion

    @Joshi As already said by my mates, you cannot store binary data in a QString.

    Just use QByteArray all the way, it is thought for things like that. QString is only for storing (unicode) text.


  • Lifetime Qt Champion


    To pile upon my fellows, currently QString stores data as UTF-16 so it's not at all suited for your purpose.

  • @aha_1980 @jsulm @SGaist @Kent-Dorfman
    It all boiled down to store some information in QSettings.
    Reading a QJsonDocument from QSettings posed an issue, however reading QString from QSettings was possible.
    Now, I found out how work with QJsonDocument and QSettings, I no longer need to wrong transfer Image in QString.
    As a work around, I changed Image to Byte Array, changed this Byte Array to hex Array and later changed this Hexed Byte array to QString and stored. But, this is all not required now.
    Thanks for your inputs.

Log in to reply