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.
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).
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) { ... }
BufferedImage buffer = ImageIO. read(new File(file)); to Image i.e in the format something like : Image image = ImageIO.
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();
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With