Created
July 1, 2020 20:46
-
-
Save Computeiful/0cef6ebd341c69df997e38e4a391cc21 to your computer and use it in GitHub Desktop.
Compress a BufferedImage to JPEG in memory
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 BufferedImage comp(BufferedImage image, float comp) throws IOException { | |
ImageWriter jpgWriter = ImageIO.getImageWritersByFormatName("jpg").next(); | |
ImageWriteParam jpgWriteParam = jpgWriter.getDefaultWriteParam(); | |
jpgWriteParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); | |
jpgWriteParam.setCompressionQuality(comp); | |
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); | |
ImageOutputStream stream = ImageIO.createImageOutputStream(outputStream); | |
jpgWriter.setOutput(stream); | |
jpgWriter.write(null, new IIOImage(image, null, null), jpgWriteParam); | |
byte[] bytes = outputStream.toByteArray(); | |
stream.close(); | |
return ImageIO.read(new ByteArrayInputStream(bytes)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment