1

I'm creating a socket-based program to send a screenshot from one user to another user. I need to convert a screenshot to a byte array before sending. After I convert my screenshot to a QByteArray I insert 4 bytes to the beginning of the array to mark that it is a picture (it is the number 20 to tell me it is a picture and not text or something else).

After I send the byte array via a socket to other user, when it is received I read the first 4 bytes to know what it is. Since it was a picture I then convert it from a QByteArray to QPixmap to show it on a label. I use secondPixmap.loadFromData(byteArray,"JPEG") to load it but it not load any picture.

This is a sample of my code:

 void MainWindow::shootScreen()
 {
     originalPixmap = QPixmap(); // clear image for low memory situations
                             // on embedded devices.
     originalPixmap = QGuiApplication::primaryScreen()->grabWindow(0);
     scaledPixmap = originalPixmap.scaled(500, 500);

     QByteArray bArray;
     QBuffer buffer(&bArray);
     buffer.open(QIODevice::WriteOnly);
     originalPixmap.save(&buffer,"JPEG",5);

     qDebug() << bArray.size() << "diz0";

     byteArray= QByteArray();

     QDataStream ds(&byteArray,QIODevice::ReadWrite);
     int32_t c = 20;
     ds << c;
     ds<<bArray;
 }

 void MainWindow::updateScreenshotLabel()
 {
     this->ui->label->setPixmap(secondPixmap.scaled(this->ui->label->size(), Qt::KeepAspectRatio, Qt::SmoothTransformation));
 }

void MainWindow::on_pushButton_clicked()
{
    shootScreen();
}

void MainWindow::on_pushButton_2_clicked()
{
    secondPixmap = QPixmap();
    QDataStream ds(&byteArray,QIODevice::ReadOnly);
    qint32 code;
    ds>>code;
    secondPixmap.loadFromData(byteArray,"JPEG");
    updateScreenshotLabel();
}
4

1 回答 1

2

您的MainWindow::on_pushButton_2_clicked实现看起来很奇怪。你有...

QDataStream ds(&byteArray,QIODevice::ReadOnly);

这将创建一个只读的QDataStream,它将从byteArray. 但是后来你...

secondPixmap.loadFromData(byteArray,"JPEG");

它试图QPixmap直接从相同 QByteArray的地方读取- 完全绕过QDataStream

您还可以使用QPixmapQDataStream. 所以我认为你正在寻找类似...

QDataStream ds(&byteArray,QIODevice::ReadOnly);
qint32 code;
ds >> code;
if (code == 20)
  ds >> secondPixmap;

同样对于您的MainWindow::shootScreen实施。您可以通过使用QDataStream & operator<<(QDataStream &stream, const QPixmap &pixmap).

于 2016-07-13T08:38:56.880 回答