Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate java BufferedImage filesize

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.

like image 506
GregA100k Avatar asked Mar 10 '09 20:03

GregA100k


People also ask

What is BufferedImage in Java?

A BufferedImage is comprised of a ColorModel and a Raster of image data. The number and types of bands in the SampleModel of the Raster must match the number and types required by the ColorModel to represent its color and alpha components. All BufferedImage objects have an upper left corner coordinate of (0, 0).

How do you write BufferedImage?

The formatName parameter selects the image format in which to save the BufferedImage . try { // retrieve image BufferedImage bi = getMyImage(); File outputfile = new File("saved. png"); ImageIO. write(bi, "png", outputfile); } catch (IOException e) { ... }

How do I change an image to BufferedImage?

BufferedImage buffer = ImageIO. read(new File(file)); to Image i.e in the format something like : Image image = ImageIO.


2 Answers

    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();
like image 68
Petr Avatar answered Sep 22 '22 13:09

Petr


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.

like image 20
Jason Cohen Avatar answered Sep 21 '22 13:09

Jason Cohen