Reputation: 1021
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.
Upvotes: 0
Views: 330
Reputation: 35276
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();
Upvotes: 2
Reputation: 2368
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();
}
}
Upvotes: 2