views:

1461

answers:

3

I have a servlet based application that is serving images from files stored locally. I have added logic that will allow the application to load the image file to a BufferedImage and then resize the image, add watermark text over the top of the image, or both.

I would like to set the content length before writing out the image. Apart from writing the image to a temporary file or byte array, is there a way to find the size of the BufferedImage?

All files are being written as jpg if that helps in calculating the size.

+5  A: 

No, you must write the file in memory or to a temporary file.

The reason is that it's impossible to predict how the JPEG encoding will affect file size.

Also, it's not good enough to "guess" at the file size; the Content-Length header has to be spot-on.

Jason Cohen
+2  A: 

Well, the BufferedImage doesn't know that it's being written as a JPEG - as far as it's concerned, it could be PNG or GIF or TGA or TIFF or BMP... and all of those have different file sizes. So I don't believe there's any way for the BufferedImage to give you a file size directly. You'll just have to write it out and count the bytes.

David Zaslavsky
A: 

Unless it is a very small image file, prefer to use chunked encoding over specifying a content length.

It was noted in one or two recent stackoverflow podcasts that HTTP proxies often report that they only support HTTP/1.0, which may be an issue.

Tom Hawtin - tackline