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.