tags:

views:

88

answers:

2

I'm working on a Java program that needs to send an image (preferably in PNG format, though I could perhaps use another format if necessary) over the network. The logical way to do this is, of course, to first send the length of the PNG image data, then the data itself. Problem: I don't see any method in ImageIO or anywhere else that will give me the length of the image data. Does this exist somewhere in the Java 1.6 standard library?

I know I could just write it to a ByteArrayOutputStream and get the length of the resulting array, but before resorting that I wanted to make sure I'm not missing something built in. And besides, that makes an extra copy of the image data, which I'd rather not do if it's not necessary.

+2  A: 

This information is not available since the final content length is not exactly predictable beforehand. You would need to generate the entire image first.


On the other hand, what network protocol are you using? You may want to check if the protocol in question supports sending the data in chunks.

To take HTTP as an example, you can use Transfer-Encoding: chunked for this. With this you can make use of a byte[] buffer to send the chunks. Basically, first send a chunk header denoting the chunk length, then a CRLF and then the whole chunk and then two CRLF's and so on until end of stream and then send a chunk header of 0 length.

You can of course also invent your own proprietary network protocol with different encodings, but it'll be after all easy if you use a standard protocol like HTTP since there exist lot of API-provided or 3rd party tools for this like java.net.URLConnection and Apache HttpComponents Client, both of which has builtin support for sending data in chunks as well.

See also:

BalusC
+1 good idea with the chunking. I'm not using HTTP, though, just a plain socket, because both the client and server are apps that I'm writing and I just wanted to get the data from one to the other with a minimum of fuss. (Basically it's an IPC setup, I'm just using a socket because it was quick to implement) Given the ubiquity of HTTP client and server libraries maybe I'll switch to that one day.
David Zaslavsky
A: 

Of course, if you used SVG this would be really simple.

Meiscooldude
Indeed, but this same image data needs to be displayed in a browser later on, and I don't think browser support for SVG is that good yet. Besides I'm not quite sure how I'd generate the image (in Java) as a vector graphic in the first place.
David Zaslavsky