* @throws IOException if an I/O error occurs
*/
public static boolean writeImage(BufferedImage image, String formatName, OutputStream output,
int dpi, float quality) throws IOException
{
ImageOutputStream imageOutput = null;
ImageWriter writer = null;
try
{
// find suitable image writer
Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName(formatName);
ImageWriteParam param = null;
IIOMetadata metadata = null;
// Loop until we get the best driver, i.e. one that supports
// setting dpi in the standard metadata format; however we'd also
// accept a driver that can't, if a better one can't be found
while (writers.hasNext())
{
if (writer != null)
{
writer.dispose();
}
writer = writers.next();
param = writer.getDefaultWriteParam();
metadata = writer.getDefaultImageMetadata(new ImageTypeSpecifier(image), param);
if (metadata != null
&& !metadata.isReadOnly()
&& metadata.isStandardMetadataFormatSupported())
{
break;
}
}
if (writer == null)
{
LOG.error("No ImageWriter found for '" + formatName + "' format");
StringBuilder sb = new StringBuilder();
String[] writerFormatNames = ImageIO.getWriterFormatNames();
for (String fmt : writerFormatNames)
{
sb.append(fmt);
sb.append(' ');
}
LOG.error("Supported formats: " + sb);
return false;
}
// compression
if (param != null && param.canWriteCompressed())
{
param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
if (formatName.toLowerCase().startsWith("tif"))
{
// TIFF compression
TIFFUtil.setCompressionType(param, image);
}
else
{
param.setCompressionType(param.getCompressionTypes()[0]);
param.setCompressionQuality(quality);
}
}
if (formatName.toLowerCase().startsWith("tif"))
{
// TIFF metadata
TIFFUtil.updateMetadata(metadata, image, dpi);
}
else if ("jpeg".equals(formatName.toLowerCase())
|| "jpg".equals(formatName.toLowerCase()))
{
// This segment must be run before other meta operations,
// or else "IIOInvalidTreeException: Invalid node: app0JFIF"
// The other (general) "meta" methods may not be used, because
// this will break the reading of the meta data in tests
JPEGUtil.updateMetadata(metadata, dpi);
}
else
{
// write metadata is possible
if (metadata != null
&& !metadata.isReadOnly()
&& metadata.isStandardMetadataFormatSupported())
{
setDPI(metadata, dpi, formatName);
}
}
// write
imageOutput = ImageIO.createImageOutputStream(output);
writer.setOutput(imageOutput);
writer.write(null, new IIOImage(image, null, metadata), param);
}
finally
{
if (writer != null)
{
writer.dispose();
}
if (imageOutput != null)
{
imageOutput.close();
}
}
return true;
}