2

I need to encode an already-created QImage into a QByteArray to send to a socket, and decode it on the another side.

On the server side, I'm trying to do something like:

// The vector is mandatory. The class that creates the image line expects it.

QVector<unsigned char> msg;  
QImage line(create_image_line(msg));

QByteArray ba((char*)line.bits(), line.numBytes());
for (int i = 0; i < ba.size(); ++i) {
  msg.append(ba[i]);
}

send_msg(msg);

The create_image_line does something like:

... handle the msg and get the image properties...
QImage img(pixels_, 1, QImage::Format_RGB32);
... set the values ...
return(img);

And on the client side:

receive_msg(msg);
QByteArray ba;
for (int i = 0; i < msg.size(); ++i) {
  ba.append(msg[i]);
}

QImage line(LINE_WIDTH, 1, QImage::Format_RGB32);
line.fromData(ba);

Something goes wrong, and the image is shown with a lot of noise (I know that the problem is located in this conversion, due another successful tests).

I'd like to know where is the problem.

Rgds.

Etore Marcari Jr.
  • 572
  • 2
  • 10
  • 19

1 Answers1

4

QImage::fromData does not retain the format, it tries to probe for a file header. It's also a static function, so it does not modify line (which stays uninitialized), it returns an image (which you discard). And it's concent of format is things like PNG or JPG, not pixel formats like the constructor.

So to do the way you have it now, you need to loop through line.bits again copying in the pixels.

However, QDataStream can serialize most of the Qt value types, including QImage. If you're in control of both ends and open to changing the protocol, this is probably a much simpler and robust solution.

sKhan
  • 9,694
  • 16
  • 55
  • 53
puetzk
  • 10,534
  • 3
  • 28
  • 32