开发者

Get file size of BufferedImage before writing the data

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 necess开发者_C百科ary) 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.


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:

  • Chunked Transfer Encoding in Wikipedia
  • Answer containing an example of ChunkedOutputStream which may be of use


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜