How to calculate java BufferedImage filesize

后端 未结 6 1468
闹比i
闹比i 2021-01-04 04:41

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 Buffered

相关标签:
6条回答
  • 2021-01-04 04:47

    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.

    0 讨论(0)
  • 2021-01-04 05:00
        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();
    
    0 讨论(0)
  • 2021-01-04 05:00

    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.

    0 讨论(0)
  • 2021-01-04 05:06

    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.

    0 讨论(0)
  • 2021-01-04 05:06

    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);`
    
    0 讨论(0)
  • 2021-01-04 05:08

    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.

    0 讨论(0)
提交回复
热议问题