如何将 QImage 从 QLocalServer 传输到 QLocalSocket

how to transfer QImage from QLocalServer to QLocalSocket

我有两个 mac 应用程序,它们使用 QLocalSocket 相互通信。 能够发送接收到的 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));
    });

发件人 262144 是字节数组大小 但在接收方,字节数组大小为 0

如果我遗漏了什么,请告诉我。

提前致谢

终于得到解决方法我用QDataStream 下面是代码示例。

服务器端代码:

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

客户端代码

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;
  }
}

谢谢大家对Whosebug的支持。