How to calculate java BufferedImage filesize

GregA100k picture GregA100k · Mar 10, 2009 · Viewed 28.5k times · Source

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.

Answer

Petr picture Petr · Feb 9, 2011
    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();