18

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.

GregA100k
  • 1,385
  • 1
  • 11
  • 16

6 Answers6

22
    BufferedImage img = = new BufferedImage(500, 300, BufferedImage.TYPE_INT_RGB);

    ByteArrayOutputStream tmp = new ByteArrayOutputStream();
    ImageIO.write(img, "png", tmp);
    tmp.close();
    Integer contentLength = tmp.size();

    response.setContentType("image/png");
    response.setHeader("Content-Length",contentLength.toString());
    OutputStream out = response.getOutputStream();
    out.write(tmp.toByteArray());
    out.close();
Petr
  • 221
  • 2
  • 2
17

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
  • 81,399
  • 26
  • 107
  • 114
6

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 Z
  • 128,184
  • 27
  • 255
  • 279
5

You can calculate the size of a BufferedImage in memory very easily. This is because it is a wrapper for a WritableRaster that uses a DataBuffer for it's backing. If you want to calculate it's size in memory you can get a copy of the image's raster using getData() and then measuring the size of the data buffer in the raster.

DataBuffer dataBuffer = bufImg.getData().getDataBuffer();

// Each bank element in the data buffer is a 32-bit integer
long sizeBytes = ((long) dataBuffer.getSize()) * 4l;
long sizeMB = sizeBytes / (1024l * 1024l);`
Verna Smith
  • 51
  • 1
  • 3
2

Before you load the image file as a BufferedImage make a reference to the image file via the File object.

File imgObj = new File("your Image file path");
int imgLength = (int) imgObj.length();

imgLength would be your approximate image size though it my vary after resizing and then any operations you perform on it.

vpointer
  • 71
  • 7
2

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
  • 145,806
  • 30
  • 211
  • 305