Send an image over a network using Qt

A question that pops up every now and again and this time I'll document my attempt to do this. To do this I use the Qt framework. More specifically, I used QtcpSocket for the connection.

In this example program I will use a client-server approach to this problem. I will build a server that accepts one or more connections and can receive images. I will also build a client that can connect to the server and send an image.

The Client-Server architecture

Most of the code that set up the actuall connection have been borrowed from the Simple Chat program. In this example a client-server system is build. What I removed from this example is all the GUI interfacing and the functions that receive and send the messages. The first is because I do not need a GUI here as I will use it as a lib, and the latter is because I do not need to send and receive QString objects (and more important, I do not have to forward them to all other connected clients).

So If you want a deeper understanding of how the connection is set-up and how the server deals with multiple connections, then I point forward to the wiki at qtcentre.org.

How to send an image

Here I will actually cover how to send an image. In Qt this is rather easy. For the sake of structure, I will first describe the client-side process and then the server-side process.

Sending the image (Client-side process)

What I need to do is to convert the image to a byte-array and then send this byte-array over the network. As we are using the Qt framework, I assume that the image is already a QImage object and the socket has been set-up by following the Simple chat example. Then sending the image is rather easy:

// To load a QImage
//QImage image;        // See the documentation on how to use QImage objects
//image.load("test.png", "PNG");
// To set-up the socket
//socket->connectToHost(address, port, QIODevice::WriteOnly)

QByteArray ba;              // Construct a QByteArray object
QBuffer buffer(&ba);        // Construct a QBuffer object using the QbyteArray
image.save(&buffer, "PNG"); // Save the QImage data into the QBuffer
socket->write(ba);          // Send the QBuffer (QbyteArray) over a socket

And that is it! Yes, there are some beautifications possible, but this is the trick!

Receiving the image (Server-side process)

Here I need to convert the incoming stream back into an image. This is basically as easy as sending it, but I will anyway show it. Also here I assume that there is a listening socket available, but I also assume that the buffer. This time no example code on that, as it takes more lines to describe.

// Available are:
//QTcpSocket* socket;
//QBuffer* buffer = buffers.value(socket);
qint64 bytes = buffer->write(socket->readAll()); // Read all the received bytes
buffer->seek(buffer->pos() - bytes);  // go back as many bytes as we just wrote so that it can be read
QImage image;			      // Construct a new QImage
image.loadFromData(buffer->buffer()); // Load the image from the receive buffer
if (image.isNull())		      // Check if the image was indeed received
        qDebug("The image is null. Something failed.");
// If it did not fail, the image is now in the QImage object again

It could hardly be simpler, isn't it?

Extra: Send the image name as well

If you want the client-side to give a name to this image then this is perfectly possible by using some interesting options from the QImage object. To attach the image name as a tag to the image use:

//QImage image has already  been constructed
image.setText("name", name);

On the receiving end we can retrieve this tag information easily using:

//QImage image has already  been constructed
image.text("name")

This leaves us with a lot of interesting possibilities... so be sure you check those out as well!

Final notes

Well, I took also the liberty to put this in code so you can download it, test it, and learn from it. You can find the source code here.

If you have any comments or questions on the code then leave a comment below or send me an e-mail. If you make some changes in the code then I am happy to receive those changes as well (as diff or as new zip file).

I hope this was helpful for you!

Comments

Anonymous (not verified)

 Hey, the code examples look good. I wanted to look at the total program and source code so I could have a better idea of what was going on. Anyway you could email it to me? or check the link?
 
Thanks

VIVEK (not verified)

qDebug() << QImageReader::supportedImageFormats () << "WE R HERE";
image->load("abc","png");
qDebug() << QImageReader::supportedImageFormats () << "WE R HERE";
QByteArray ba; // Construct a QByteArray object
QBuffer buffer(&ba); // Construct a QBuffer object using the QbyteArray
image->save(&buffer, "PNG"); // Save the QImage data into the QBuffer
socket->write(ba);

OUTPUT:
("bmp", "gif", "ico", "jpeg", "jpg", "mng", "pbm", "pgm", "png", "ppm", "svg", "svgz", "tif", "tiff", "xbm", "xpm")
The program has unexpectedly finished.WE R HERE

patrick

Where did you get an error in the _original_ code?
Or
Where did you change the code and then where did you get an error?

The text you copy-pasted above is not very useful for me! Don't hesitate to ask me for more info!

Vivek (not verified)

Image load failed from sender side and as a result receiver is receiving empty file. What might be problem. Its working fine on machine where qt is installed but not working on machine where qt is not installed.

Jerry (not verified)

I have tried different ways to save a received image file over the network using sockets to file. This what i have done so far:
/******************Code**************************/
QBuffer *ImageBuffer = new QBuffer;
qint64 bytes = ImageBuffer->write(socket->readAll());
ImageBuffer->seek(ImageBuffer->pos() - bytes);
recvdImage.loadFromData(ImageBuffer->buffer());
if(!recvdImage.isNull()){
qDebug() << "Image file was received ";
}
/******************End of Code**************************/

I get an error on the server console:
QBuffer::seek: Invalid pos:1;

I get some image data from clients through the socket, I would like to save it to a file as png, jpg. So that I can do further analysis on that.

Any help will be greatly appreciated, thanks.

patrick

If you get an error server-side, then please provide the server side code. The client-side code seems oke... but will not help me (or you) to debug. If you do not want to past it, then send it to me via e-mail!

Jerry (not verified)

Hi Patrick..this is the server side code, the client is an android phone sending an image. i can't seem to get the image file in full, please help. The client is sending the data in int64.

patrick

Aha... we are confused over what is a server and what is a client. So... let me rephrase:

The issue seems to be on the sender side (which I called the server), since the code on the receiving end seems fine. So, I need to see how you provide the data.

Did you try to write a sender in Qt?
Did you try the sender I describe in this blog-post?

Please, first try that!
If you get an error in that case... then I can help.
If not, then I need to see the android code... but I have little experience with Android... so no promisses there!

P

PS. If you want to contact me directly, you can find my e-mail address on the "Contact" page!

Saravanan (not verified)

I have tried the above code.But I am implementing the same code in QT installed in Raspberry Pi.
I need to send an image to the modem by using QT.I need to convert the image into the byte format and then send the same to the GSM modem.Can you guide me in this issue.Thanks in advance.

Pages

© 2008 - 2014 Patrick Hanckmann

View Patrick Hanckmann's profile on LinkedIn