QT failed to load Image from Buffer

1.4k views Asked by At

My work Environment : Qt 5.8 MSVC2015 64bit, QT GraphicsView, Windows 7 64 bit

I am loading image from buffer (a demon process is going send a image buffer), but it failed to create image with buffer.

QFile file("D:\\2.png");
if (!file.open(QFile::ReadOnly))
    qDebug() << "Error failed to Open file";
QByteArray array = file.readAll();
array = array.toBase64();
QImage tempimage((uchar *)array.data(), 250, 250, QImage::Format_RGBX8888);
if (!tempimage.isNull()) {
      ///I always get this error
    qDebug() << "Error!!! failed to create a image!"; 
}

Any idea what I am missing here ?

2

There are 2 answers

0
James Poag On

Why are you converting to base64?

Wait, where are you converting from PNG to an image plane?

Try bool QImage::loadFromData(const QByteArray &data, const char *format = Q_NULLPTR) to load the PNG instead of the CTor with the raw data.

If your wire format isn't PNG (and is in fact base64 encoded raw pixel data) then you want to convert FROM base64.

0
Sandip On

Thanks for all suggestion & help. I fix my mistakes removed base64 conversion & loaded buffer using loadFromData with QByteArray reinterpret_cast:

Here is a final solution :

QFile file("D:\\2.png");
if (!file.open(QFile::ReadOnly))
    qDebug() << "Error failed to Open file";
QByteArray array = file.readAll();

 QImage tempimage;
 //// This very important to cast in below format, QByteArray don't work as arguments.
 tempimage.loadFromData(reinterpret_cast<const uchar *>(array.data()),array.size());
if (tempimage.isNull()) {
    qDebug() << "Error!!! failed to create a image!";
}