Sending images over a socket using qt and reading it using java

I am trying to send an image upload to a Qt server through a socket and render it on a client created using Java. So far, I have only passed strings for communication from both sides and tried different examples for sending images, but without any results.

The code I used to transfer the image to qt is:

QImage image; image.load("../punton.png"); qDebug()<<"Image loaded"; QByteArray ban; // Construct a QByteArray object QBuffer buffer(&ban); // Construct a QBuffer object using the QbyteArray image.save(&buffer, "PNG"); // Save the QImage data into the QBuffer socket->write(ban); 

At the other end, code for reading in Java:

 BufferedInputStream in = new BufferedInputStream(socket.getInputStream(),1); File f = new File("C:\\Users\\CLOUDMOTO\\Desktop\\JAVA\\image.png"); System.out.println("Receiving..."); FileOutputStream fout = new FileOutputStream(f); byte[] by = new byte[1]; for(int len; (len = in.read(by)) > 0;){ fout.write(by, 0, len); System.out.println("Done!"); } 

The process in Java gets stuck until I close the Qt server, and after that the created file is corrupted.

I will be grateful for any help, because it is necessary for me, and I am new to programming in both languages.

I also used the following commands, which now complete the receiving process and display a message, but the file is damaged.

 socket->write(ban+"-1"); socket->close(); in qt. 

And in java:

 System.out.println(by); String received = new String(by, 0, by.length, "ISO8859_1"); System.out.println(received); System.out.println("Done!"); 

enter image description here

+4
source share
1 answer

You cannot transfer a file through a socket in such a simple way. You do not give the receiver any clue how many bytes are appropriate. Read the javadoc carefully for InputStream.read () . Your receiver is in an infinite loop because it waits for the next byte until the stream is closed. Thus, you partially fixed this by calling socket->close() on the sender side. Ideally, you need to write the ban length to the socket in front of the buffer, read that length on the receiver side, and then get only that number of bytes. Also flush and close receiver stream before trying to read the received file.

I have no idea what you wanted to achieve with socket->write(ban+"-1") . The recorded result starts with %PNG , which is correct. I see "-1" at the end, which means that you added characters to the binary image file, therefore, you messed it up. Why is that?

And no, 1x1 PNG is not 1 byte in size. It does not even have 4 bytes (red, green, blue, alpha). PNG needs some things, such as header and control checksum. See the file size in the file system. This is your size by .

+1
source

Source: https://habr.com/ru/post/1441180/


All Articles