Skip to content

Instantly share code, notes, and snippets.

@worthlesscog
Created July 1, 2012 08:35
Show Gist options
  • Save worthlesscog/3027566 to your computer and use it in GitHub Desktop.
Save worthlesscog/3027566 to your computer and use it in GitHub Desktop.
Image compress and save helpers
private void buildImage(BufferedImage sourceImage, int width, int height, String imageType, Object target, float quality) throws IOException {
ImageWriter imageWriter = writerFor(imageType, target);
ImageWriteParam imageWriteParam = compressionParametersFor(imageWriter, quality);
imageWriter.write(null, new IIOImage(sourceImage, null, null), imageWriteParam);
imageWriter.dispose();
}
private ImageWriter writerFor(String imageType, Object target) throws IOException {
ImageWriter imageWriter = ImageIO.getImageWritersByFormatName(imageType).next();
imageWriter.setOutput(target);
return imageWriter;
}
private ImageWriteParam compressionParametersFor(ImageWriter imageWriter, float quality) {
ImageWriteParam imageWriteParam = imageWriter.getDefaultWriteParam();
imageWriteParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
imageWriteParam.setCompressionQuality(quality);
return imageWriteParam;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment