1

I want to compress jpg file if it bigger than 1MB to 1MB or a bit smaller. Param compressionQuality from 0.0f to 1.0f in setCompressionQuality in ImageWriteParam is not clearly defined.

Quality = 0.5f can compress the image 5 times, 7 times, 1.2 times depends on the image. Not 2 times as everybody expected.

So, how can I choose the size of compressing image? Maybe there are any open source libraries?

UPD: Example of compressing:

public static byte[] write(BufferedImage image, String formatName, int dpi, float quality) {
    try(ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
        ImageIOUtil.writeImage(image, formatName, outputStream, dpi, quality);
        return outputStream.toByteArray();
    } catch (IOException ex) {
        return null;
    }
}

public static void main(String[] args) {
    BufferedImage bufImg = null;
    try
    {
        bufImg = ImageIO.read(new File("myfile"));
    } catch (IOException e){e.printStackTrace();}

    for(int i = 0; i < 10; i++) {
        byte[] arr = write(bufImg, "jpg", 300, 0.1f*i);
        double fl = (double)arr.length/(double)MY_FILE_SIZE_BYTES;

        System.out.println(fl + " " + (0.1f*i));
    }
}

I use org.apache.pdfbox.tools.imageio.ImageIOUtil for that, ImageIOUtil uses ImageWriter and ImageWriteParam inside.

  • Could you provide the code you use to compress images right now? – theblackips Jul 03 '19 at 12:26
  • You could guess the quality needed based on the size of the original image; based on the result, make a better guess at the quality needed to get the desired result; repeat until you are satisfied. – Scott Hunter Jul 03 '19 at 12:31
  • @ScottHunter I dont want to guess the quality, server can receive a lot of images in 5 seconds. Now I am guessing and server does not cope with the load. – Kamitonishe Jul 03 '19 at 12:38
  • 2
    Answers to https://stackoverflow.com/q/56870530/535275 may reduce the overhead of guessing. The alternative is to do some kind of analysis, which is probably comparable in computational effort. – Scott Hunter Jul 03 '19 at 13:03

0 Answers0