Last active
January 17, 2019 07:22
-
-
Save faizakram/aa341ec67661e17fcf3c047627414128 to your computer and use it in GitHub Desktop.
Image Compress - JPG, PNG
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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