Hello, the next question. Programmatically (in Java) I save images in Jpeg format using the ImageIO.write() method. As you know, in this case, the picture is stored in the standard for Jpeg 24-bit color depth. Image sizes in pixels are known. How to at least roughly predict the size of the image in bytes after saving?

As practice has shown, the formula (Π΄Π»ΠΈΠ½Π° Π² пикс.)*(ΡˆΠΈΡ€ΠΈΠ½Π° Π² пикс)*(3 Π±Π°ΠΉΡ‚Π°) does not give correct results.

  • psychic cause?)) - Gorets 2:38 pm
  • No, as I understand it, you need to find out the compression level of Jpeg, which is used by the ImageIO.write () method. "Formula" (for those who understand it, of course, is ridiculous) wrote that there were no answers like "multiply the length by the width and ..." - Selden
  • if it is difficult to find a formula, try to derive it yourself, conduct an experiment =) - Gorets
  • 2
    Due to the specificity of the JPEG algorithm, it is difficult to estimate the size of the image in advance. Perhaps it makes sense to try to somehow convert the images in memory before saving to a file and in memory to estimate the size. - Nicolas Chabanovsky ♦

1 answer 1

Is done. For large images, I calculate the size approximately, taking into account the compression level of Jpeg (manually set 100%). For those that are smaller than 5 MB, I calculate the size on the fly:

 ByteArrayOutputStream bos = new ByteArrayOutputStream(); ImageIO.write(img, "JPEG", bos); long fileSizeAfter = bos.toByteArray().length; 
  • four
    You can do better. In order not to waste memory, you can create your own OutputStream, which only counts the bytes written into it and does not save it anywhere. Then you can calculate everything and not spend memory to store the resulting JPEG. - cy6erGn0m
  • You are right, thanks! - Selden