What is the general approach to compress an image to JPEG with a target 100kb size? Either lowering the "bitrate", automatically resizing the image, both?
That is, using pure Java and no external "native" dependencies.
What is the general approach to compress an image to JPEG with a target 100kb size? Either lowering the "bitrate", automatically resizing the image, both?
That is, using pure Java and no external "native" dependencies.
Another option is to use: https://github.com/fewlaps/slim-jpg
Result result = SlimJpg.file(imageBytes)
.maxVisualDiff(0.5)
.maxFileWeightInKB(100)
.deleteMetadata()
.optimize();
byte[] compressedBytes = result.getPicture();
You can use the Java ImageIO
package to do the compression using pure Java. You have the documentaion here: javax.imageio
Here is an example how to use it, the example is from this thread if you want to read more about it: How can I compress images using java?
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Iterator;
import javax.imageio.*;
import javax.imageio.stream.*;
public class Compresssion {
public static void main(String[] args) throws IOException {
File input = new File("original_image.jpg");
BufferedImage image = ImageIO.read(input);
File compressedImageFile = new File("compressed_image.jpg");
OutputStream os = new FileOutputStream(compressedImageFile);
Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName("jpg");
ImageWriter writer = (ImageWriter) writers.next();
ImageOutputStream ios = ImageIO.createImageOutputStream(os);
writer.setOutput(ios);
ImageWriteParam param = writer.getDefaultWriteParam();
param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
param.setCompressionQuality(0.05f); // Change the quality value you prefer
writer.write(null, new IIOImage(image, null, null), param);
os.close();
ios.close();
writer.dispose();
}
}