if (IndexImageBuilder.needConvertToIndex(images[0])) {
img = IndexImageBuilder.createIndexedImage(images[0], quantAlg);
}
ImageIO.write(img, "GIF", imageOut);
} catch (IOException e) {
throw new SimpleImageException(e);
} finally {
ImageUtils.closeQuietly(imageOut);
}
return;
}
try {
imageOut = ImageIO.createImageOutputStream(os);
Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName("GIF");
while (writers.hasNext()) {
writer = writers.next();
if (writer.canWriteSequence()) {
break;
}
}
if (writer == null || !writer.canWriteSequence()) {
throw new IllegalStateException("No GIF writer matched");
}
writer.setOutput(imageOut);
ImageWriteParam param = writer.getDefaultWriteParam();
IIOMetadata streamMeta = writer.getDefaultStreamMetadata(param);
//merge stream metadata
streamMeta.mergeTree(ImageWrapper.GIF_STREAM_METADATA_NAME, imgWrapper.getStreamMetadata());
writer.prepareWriteSequence(streamMeta);
for (int i = 0; i < images.length; i++) {
ImageTypeSpecifier imageType = new ImageTypeSpecifier(images[i].getColorModel(),
images[i].getSampleModel());
RenderedImage renderedImg = images[i];
if (IndexImageBuilder.needConvertToIndex(renderedImg)) {
NodeUtils.removeChild(metadatas[i], "LocalColorTable");
renderedImg = IndexImageBuilder.createIndexedImage(renderedImg, quantAlg);
}
IIOMetadata meta = writer.getDefaultImageMetadata(imageType, param);
meta.mergeTree(ImageWrapper.GIF_IMAGE_METADATA_NAME, metadatas[i]);
IIOImage img = new IIOImage(renderedImg, null, meta);
writer.writeToSequence(img, param);
}
writer.endWriteSequence();
imageOut.flush();
} catch (IOException e) {
throw new SimpleImageException(e);
} finally {
ImageUtils.closeQuietly(imageOut);
if (writer != null) {
writer.dispose();