简体   繁体   English

如何将 QImage 从 QLocalServer 传输到 QLocalSocket

[英]how to transfer QImage from QLocalServer to QLocalSocket

I have two mac apps that communicate with each other using QLocalSocket.我有两个使用 QLocalSocket 相互通信的 mac 应用程序。 Able to send the received QString but not able to send the received QImage Below is my code.能够发送接收到的 QString 但不能发送接收到的 QImage 下面是我的代码。

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在发送方 262144 是字节数组大小,但在接收方,字节数组大小为 0

Do let me know if I am missing anything.如果我遗漏了什么,请告诉我。

Thanks In Advance提前致谢

Finally I got the solutions I used QDataStream below is the code example.最后我得到了我使用 QDataStream 的解决方案,下面是代码示例。

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.谢谢大家对 Stackoverflow 的支持。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM