How to calculate java BufferedImage filesize

眉间皱痕 提交于 2019-11-30 17:35:00

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.

    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();

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.

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);`

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!