how to transfer QImage from QLocalServer to QLocalSocket

I have two mac apps that communicate with each other using QLocalSocket. Able to send the received QString but not able to send the received QImage Below is my code.

SERVER SIDE CODE

 QImage image(":/asset/logo_active.png");
 QByteArray ba;
 qDebug() << image.sizeInBytes() <<image.size();
 ba.append((char *)image.bits(),image.sizeInBytes());
 qDebug() <<ba.size(); //262144
 this->mSocket->write(ba);
 if(!this->mSocket->waitForBytesWritten(-1))
 {
     qDebug() << "writen Bytes error " << this->mSocket->errorString();
 }
 this->mSocket->flush();

CLIENT SIDE CODE

    connect(mLocalSocket,&QLocalSocket::readyRead, [&]() {
        QByteArray ba;
        ba = mLocalSocket->readAll();
qDebug() << "size is" << ba.size(); // size is 0
        QImage image((uchar *)ba.data(),1024,768,QImage::Format_RGB32);
        ui->labelStream->setPixmap(QPixmap::fromImage(img));
    });

at sender 262144 is the byte-array size but at the receiver, byte-array size is 0

Do let me know if I am missing anything.

Thanks In Advance

1 answer

  • answered 2022-04-12 06:40 Mohammed Ebrahim

    Finally I got the solutions I used QDataStream below is the code example.

    SERVER SIDE CODE:

     QDataStream T(mSocket);
     T.setVersion(QDataStream::Qt_5_7);
     QByteArray ba;
     ba.append((char *)img.bits(),img.sizeInBytes());
     T << ba;
     mSocket->flush();
    

    CLIENT SIDE CODE

    QByteArray jsonData;
    QDataStream socketStream(mLocalSocket);
    socketStream.setVersion(QDataStream::Qt_5_7);
    
    for (;;) {
     socketStream.startTransaction();
     socketStream >> jsonData;
     if (socketStream.commitTransaction()) {
      QImage image((uchar *)jsonData.data(),640,480,QImage::Format_RGB888);
      ui->labelStream->setPixmap(QPixmap::fromImage(image));
     }else {
                      // the read failed, the socket goes automatically back to the state it was in before the transaction started
                      // we just exit the loop and wait for more data to become available
                      break;
      }
    }
    

    Thanks, Everyone for your support also Stackoverflow.

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum