PDA

View Full Version : Send QImage over network



winston2020
19th March 2009, 22:19
Hi, I'm trying to send a QImage through QTcpSockets, but the data always comes out corrupted on the receiving end.

What's the most direct way of writing and reading the image?

wysota
19th March 2009, 22:35
The most direct way is to write the data directly to the socket and read it the same way on the other end. But if you provide the code you wrote to write and feed and retrieve the image from the socket, maybe we'll be able to tell what mistakes you have made.

winston2020
19th March 2009, 22:46
I've tried several approaches. The main problem is retrieving the actual data from the QImage class, and building a new QImage object from that data on the other side.

I tried using QImageWriter to write the image to a file on the hdd, and then using QFile, read the data, and transmit the QByteArray over the socket:



// This code is inside my subclass of QTcpSocket
QImageWriter writer( QString("image.jpg"), "jpg" );
writer.write(image);

QFile imageFile( QString("image.jpg"), this );
QByteArray data = imageFile.readAll();

if(write(data))
emit writeln(tr("Write Successful"));


Then on the other side I just do this:


QByteArray data = readAll();
QFile out(tr("output.jpg"));
out.open( QIODevice::ReadWrite );
out.write(data);
out.close();


However, I also tried wrapping the QTcpSocket with QImageWriter, and transmitting that way:



QImageWriter writer( this, "jpg" );
writer.write(image);

wysota
20th March 2009, 01:30
Have you checked that the appropriate amount of data is ready to be read on the receiving end? The fact that you are notified there is something to be read doesn't mean there is everything to be read, maybe that's the problem?

winston2020
20th March 2009, 18:46
Have you checked that the appropriate amount of data is ready to be read on the receiving end? The fact that you are notified there is something to be read doesn't mean there is everything to be read, maybe that's the problem?

Thank you for your help. I'm still quite new to network programming in QT. Right now I'm using QIODevice::readyRead() signal to notify my socket when to begin reading. Is that incorrect? How should I determine when the reading should begin?

I tried sending the size of the file first, but I find that readyRead() is emitted several times for each transfer.

caduel
20th March 2009, 19:09
it is ok to begin reading. the point is when to stop.
because unless you send the package size (before the image data) you will never know if the image is complete.

see network-fortuneclient for an example to wait for a complete package of network data

hth