if (formatName == null) {
throw new IllegalArgumentException("formatName == null!");
}
// create the output stream
ImageOutputStream stream = null;
try {
stream = ImageIO.createImageOutputStream(output);
} catch (IOException e) {
throw new IIOException("Can't create output stream!", e);
}
// make sure we have our exact constants to work with
formatName = getImageType(formatName);
if (formatName == null) {
throw new IllegalArgumentException("no writers found for format '" + formatName + "'");
}
// make sure there are no transparent pixels left if not supported by the written image format
if (im.getColorModel().hasAlpha()
&& ((TYPE_JPEG == formatName) || (TYPE_TIFF == formatName) || (TYPE_BMP == formatName))) {
// several formats do not support alpha
BufferedImage result = new BufferedImage(im.getWidth(), im.getHeight(), BufferedImage.TYPE_INT_RGB);
Graphics2D g = result.createGraphics();
g.setPaintMode();
g.setColor(m_renderSettings.getTransparentReplaceColor());
g.fillRect(0, 0, result.getWidth(), result.getHeight());
g.drawImage(im, 0, 0, null);
g.dispose();
im = result;
}
// obtain the writer for the image
// this must work since it is already done in the #getImageType(String) call above
ImageWriter writer = (ImageWriter)ImageIO.getImageWritersByFormatName(formatName).next();
// get default image writer parameter
ImageWriteParam param = writer.getDefaultWriteParam();
if (param.canWriteCompressed()) {
// set compression parameters if supported by writer
param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
if ((param.getCompressionTypes() != null) && (param.getCompressionType() == null)) {
// a compression parameter is required but not provided, use the first one available
param.setCompressionType(param.getCompressionTypes()[0]);
}
param.setCompressionQuality(m_renderSettings.getCompressionQuality());
}
// now write the image
writer.setOutput(stream);
writer.write(null, new IIOImage(im, null, null), param);
stream.flush();
writer.dispose();
stream.close();
}