使用toUtf8()将QString转换为QByteArray,导致QByteArray具有额外的字符

时间:2019-04-05 07:18:43

标签: qstring qbytearray

当我将QString转换为QByteArray时,我看到QByteArray还有一些其他字符。

我需要它以字符串格式存储图像,然后读取字符串,将该字符串转换为Qbytearray并将图像加载回去。

void WorkWithImagesForSerialization_1()
{
    QImage original_image("someicon.png");
    if (original_image.isNull() != true)
    {
        QByteArray original_bytearray;
        QBuffer original_buffer(&original_bytearray);
        original_buffer.open(QIODevice::WriteOnly);
        original_image.save(&original_buffer, "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.loadFromData(second_bytearray);
        // second_image is null here
    }
}

我希望QByteArray转换应该正确,以便我可以重新加载图像。

0 个答案:

没有答案