Here is a way to save BufferedImage as JEPG using ImageWriter.
public static void writeAsJpeg(BufferedImage image, float quality, File outputFile) throws IOException {
ImageWriter writer = getImageWriter("jpg");
JPEGImageWriteParam iwp = new JPEGImageWriteParam(Locale.getDefault());
iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
iwp.setCompressionQuality(quality);
try (ImageOutputStream ios = ImageIO.createImageOutputStream(outputFile)){
writer.setOutput(ios);
writer.write(null, new IIOImage(image,null,null),iwp);
ios.flush();
}
finally{
writer.dispose();
}
}
private static ImageWriter getImageWriter(String ext) {
Iterator iter = ImageIO.getImageWritersByFormatName(ext);
if (iter.hasNext()) {
return iter.next();
}
throw new IllegalStateException("Unsupported " + ext);
}
コメント