Skip to content

Instantly share code, notes, and snippets.

@faizakram
Last active January 17, 2019 07:22
Show Gist options
  • Save faizakram/aa341ec67661e17fcf3c047627414128 to your computer and use it in GitHub Desktop.
Save faizakram/aa341ec67661e17fcf3c047627414128 to your computer and use it in GitHub Desktop.
Image Compress - JPG, PNG
public static byte[] compress(BufferedImage image, float scale) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName("jpg");
ImageWriter writer = writers.next();
ImageWriteParam param = writer.getDefaultWriteParam();
param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
param.setCompressionQuality(scale);
ImageOutputStream ios = ImageIO.createImageOutputStream(baos);
writer.setOutput(ios);
writer.write(null, new IIOImage(image, null, null), param);
byte[] data = baos.toByteArray();
ios.close();
baos.close();
writer.dispose();
return data;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment