Java Code Examples for javax.imageio.ImageWriter#endWriteSequence()

The following examples show how to use javax.imageio.ImageWriter#endWriteSequence() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: LUTCompareTest.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
private static Image createTestImage() throws IOException  {
    BufferedImage frame1 = createFrame(new int[] { 0xffff0000, 0xffff0000 });
    BufferedImage frame2 = createFrame(new int[] { 0xff0000ff, 0xffff0000 });

    ImageWriter writer = ImageIO.getImageWritersByFormatName("GIF").next();
    ImageOutputStream ios = ImageIO.createImageOutputStream(new File("lut_test.gif"));
    ImageWriteParam param = writer.getDefaultWriteParam();
    writer.setOutput(ios);
    writer.prepareWriteSequence(null);
    writer.writeToSequence(new IIOImage(frame1, null, null), param);
    writer.writeToSequence(new IIOImage(frame2, null, null), param);
    writer.endWriteSequence();
    writer.reset();
    writer.dispose();

    ios.flush();
    ios.close();

    return Toolkit.getDefaultToolkit().createImage("lut_test.gif");
}
 
Example 2
Source File: LUTCompareTest.java    From jdk8u-dev-jdk with GNU General Public License v2.0 6 votes vote down vote up
private static Image createTestImage() throws IOException  {
    BufferedImage frame1 = createFrame(new int[] { 0xffff0000, 0xffff0000 });
    BufferedImage frame2 = createFrame(new int[] { 0xff0000ff, 0xffff0000 });

    ImageWriter writer = ImageIO.getImageWritersByFormatName("GIF").next();
    ImageOutputStream ios = ImageIO.createImageOutputStream(new File("lut_test.gif"));
    ImageWriteParam param = writer.getDefaultWriteParam();
    writer.setOutput(ios);
    writer.prepareWriteSequence(null);
    writer.writeToSequence(new IIOImage(frame1, null, null), param);
    writer.writeToSequence(new IIOImage(frame2, null, null), param);
    writer.endWriteSequence();
    writer.reset();
    writer.dispose();

    ios.flush();
    ios.close();

    return Toolkit.getDefaultToolkit().createImage("lut_test.gif");
}
 
Example 3
Source File: LUTCompareTest.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
private static Image createTestImage() throws IOException  {
    BufferedImage frame1 = createFrame(new int[] { 0xffff0000, 0xffff0000 });
    BufferedImage frame2 = createFrame(new int[] { 0xff0000ff, 0xffff0000 });

    ImageWriter writer = ImageIO.getImageWritersByFormatName("GIF").next();
    ImageOutputStream ios = ImageIO.createImageOutputStream(new File("lut_test.gif"));
    ImageWriteParam param = writer.getDefaultWriteParam();
    writer.setOutput(ios);
    writer.prepareWriteSequence(null);
    writer.writeToSequence(new IIOImage(frame1, null, null), param);
    writer.writeToSequence(new IIOImage(frame2, null, null), param);
    writer.endWriteSequence();
    writer.reset();
    writer.dispose();

    ios.flush();
    ios.close();

    return Toolkit.getDefaultToolkit().createImage("lut_test.gif");
}
 
Example 4
Source File: LUTCompareTest.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
private static Image createTestImage() throws IOException  {
    BufferedImage frame1 = createFrame(new int[] { 0xffff0000, 0xffff0000 });
    BufferedImage frame2 = createFrame(new int[] { 0xff0000ff, 0xffff0000 });

    ImageWriter writer = ImageIO.getImageWritersByFormatName("GIF").next();
    ImageOutputStream ios = ImageIO.createImageOutputStream(new File("lut_test.gif"));
    ImageWriteParam param = writer.getDefaultWriteParam();
    writer.setOutput(ios);
    writer.prepareWriteSequence(null);
    writer.writeToSequence(new IIOImage(frame1, null, null), param);
    writer.writeToSequence(new IIOImage(frame2, null, null), param);
    writer.endWriteSequence();
    writer.reset();
    writer.dispose();

    ios.flush();
    ios.close();

    return Toolkit.getDefaultToolkit().createImage("lut_test.gif");
}
 
Example 5
Source File: LUTCompareTest.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
private static Image createTestImage() throws IOException  {
    BufferedImage frame1 = createFrame(new int[] { 0xffff0000, 0xffff0000 });
    BufferedImage frame2 = createFrame(new int[] { 0xff0000ff, 0xffff0000 });

    ImageWriter writer = ImageIO.getImageWritersByFormatName("GIF").next();
    ImageOutputStream ios = ImageIO.createImageOutputStream(new File("lut_test.gif"));
    ImageWriteParam param = writer.getDefaultWriteParam();
    writer.setOutput(ios);
    writer.prepareWriteSequence(null);
    writer.writeToSequence(new IIOImage(frame1, null, null), param);
    writer.writeToSequence(new IIOImage(frame2, null, null), param);
    writer.endWriteSequence();
    writer.reset();
    writer.dispose();

    ios.flush();
    ios.close();

    return Toolkit.getDefaultToolkit().createImage("lut_test.gif");
}
 
Example 6
Source File: LUTCompareTest.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
private static Image createTestImage() throws IOException  {
    BufferedImage frame1 = createFrame(new int[] { 0xffff0000, 0xffff0000 });
    BufferedImage frame2 = createFrame(new int[] { 0xff0000ff, 0xffff0000 });

    ImageWriter writer = ImageIO.getImageWritersByFormatName("GIF").next();
    ImageOutputStream ios = ImageIO.createImageOutputStream(new File("lut_test.gif"));
    ImageWriteParam param = writer.getDefaultWriteParam();
    writer.setOutput(ios);
    writer.prepareWriteSequence(null);
    writer.writeToSequence(new IIOImage(frame1, null, null), param);
    writer.writeToSequence(new IIOImage(frame2, null, null), param);
    writer.endWriteSequence();
    writer.reset();
    writer.dispose();

    ios.flush();
    ios.close();

    return Toolkit.getDefaultToolkit().createImage("lut_test.gif");
}
 
Example 7
Source File: LUTCompareTest.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
private static Image createTestImage() throws IOException  {
    BufferedImage frame1 = createFrame(new int[] { 0xffff0000, 0xffff0000 });
    BufferedImage frame2 = createFrame(new int[] { 0xff0000ff, 0xffff0000 });

    ImageWriter writer = ImageIO.getImageWritersByFormatName("GIF").next();
    ImageOutputStream ios = ImageIO.createImageOutputStream(new File("lut_test.gif"));
    ImageWriteParam param = writer.getDefaultWriteParam();
    writer.setOutput(ios);
    writer.prepareWriteSequence(null);
    writer.writeToSequence(new IIOImage(frame1, null, null), param);
    writer.writeToSequence(new IIOImage(frame2, null, null), param);
    writer.endWriteSequence();
    writer.reset();
    writer.dispose();

    ios.flush();
    ios.close();

    return Toolkit.getDefaultToolkit().createImage("lut_test.gif");
}
 
Example 8
Source File: LUTCompareTest.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
private static Image createTestImage() throws IOException  {
    BufferedImage frame1 = createFrame(new int[] { 0xffff0000, 0xffff0000 });
    BufferedImage frame2 = createFrame(new int[] { 0xff0000ff, 0xffff0000 });

    ImageWriter writer = ImageIO.getImageWritersByFormatName("GIF").next();
    ImageOutputStream ios = ImageIO.createImageOutputStream(new File("lut_test.gif"));
    ImageWriteParam param = writer.getDefaultWriteParam();
    writer.setOutput(ios);
    writer.prepareWriteSequence(null);
    writer.writeToSequence(new IIOImage(frame1, null, null), param);
    writer.writeToSequence(new IIOImage(frame2, null, null), param);
    writer.endWriteSequence();
    writer.reset();
    writer.dispose();

    ios.flush();
    ios.close();

    return Toolkit.getDefaultToolkit().createImage("lut_test.gif");
}
 
Example 9
Source File: LUTCompareTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
private static Image createTestImage() throws IOException  {
    BufferedImage frame1 = createFrame(new int[] { 0xffff0000, 0xffff0000 });
    BufferedImage frame2 = createFrame(new int[] { 0xff0000ff, 0xffff0000 });

    ImageWriter writer = ImageIO.getImageWritersByFormatName("GIF").next();
    ImageOutputStream ios = ImageIO.createImageOutputStream(new File("lut_test.gif"));
    ImageWriteParam param = writer.getDefaultWriteParam();
    writer.setOutput(ios);
    writer.prepareWriteSequence(null);
    writer.writeToSequence(new IIOImage(frame1, null, null), param);
    writer.writeToSequence(new IIOImage(frame2, null, null), param);
    writer.endWriteSequence();
    writer.reset();
    writer.dispose();

    ios.flush();
    ios.close();

    return Toolkit.getDefaultToolkit().createImage("lut_test.gif");
}
 
Example 10
Source File: OpaquePNGToGIFTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
public void createAnimatedImage(BufferedImage bi, IIOMetadata metadata,
        ImageWriter writer, File outputFile) {
    try {

        fos = new FileOutputStream(outputFile);
        ImageOutputStream ios = ImageIO.createImageOutputStream(fos);
        System.out.println(ios);
        writer.setOutput(ios);

        ImageWriteParam param = writer.getDefaultWriteParam();
        IIOMetadata streamData = writer.getDefaultStreamMetadata(param);

        writer.prepareWriteSequence(streamData);
        ImageTypeSpecifier specify = new ImageTypeSpecifier(bi);
        IIOMetadata imgData = writer.convertImageMetadata(
                (IIOMetadata) metadata, specify, param);
        GIFImageMetadata gifData = setAnimationProperties(imgData);
        IIOImage iim = new IIOImage(bi, null, gifData);
        param.setProgressiveMode(param.MODE_DISABLED);
        writer.writeToSequence(iim, param);
        writer.endWriteSequence();
        ios.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 11
Source File: LUTCompareTest.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
private static Image createTestImage() throws IOException  {
    BufferedImage frame1 = createFrame(new int[] { 0xffff0000, 0xffff0000 });
    BufferedImage frame2 = createFrame(new int[] { 0xff0000ff, 0xffff0000 });

    ImageWriter writer = ImageIO.getImageWritersByFormatName("GIF").next();
    ImageOutputStream ios = ImageIO.createImageOutputStream(new File("lut_test.gif"));
    ImageWriteParam param = writer.getDefaultWriteParam();
    writer.setOutput(ios);
    writer.prepareWriteSequence(null);
    writer.writeToSequence(new IIOImage(frame1, null, null), param);
    writer.writeToSequence(new IIOImage(frame2, null, null), param);
    writer.endWriteSequence();
    writer.reset();
    writer.dispose();

    ios.flush();
    ios.close();

    return Toolkit.getDefaultToolkit().createImage("lut_test.gif");
}
 
Example 12
Source File: LUTCompareTest.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
private static Image createTestImage() throws IOException  {
    BufferedImage frame1 = createFrame(new int[] { 0xffff0000, 0xffff0000 });
    BufferedImage frame2 = createFrame(new int[] { 0xff0000ff, 0xffff0000 });

    ImageWriter writer = ImageIO.getImageWritersByFormatName("GIF").next();
    ImageOutputStream ios = ImageIO.createImageOutputStream(new File("lut_test.gif"));
    ImageWriteParam param = writer.getDefaultWriteParam();
    writer.setOutput(ios);
    writer.prepareWriteSequence(null);
    writer.writeToSequence(new IIOImage(frame1, null, null), param);
    writer.writeToSequence(new IIOImage(frame2, null, null), param);
    writer.endWriteSequence();
    writer.reset();
    writer.dispose();

    ios.flush();
    ios.close();

    return Toolkit.getDefaultToolkit().createImage("lut_test.gif");
}
 
Example 13
Source File: LUTCompareTest.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
private static Image createTestImage() throws IOException  {
    BufferedImage frame1 = createFrame(new int[] { 0xffff0000, 0xffff0000 });
    BufferedImage frame2 = createFrame(new int[] { 0xff0000ff, 0xffff0000 });

    ImageWriter writer = ImageIO.getImageWritersByFormatName("GIF").next();
    ImageOutputStream ios = ImageIO.createImageOutputStream(new File("lut_test.gif"));
    ImageWriteParam param = writer.getDefaultWriteParam();
    writer.setOutput(ios);
    writer.prepareWriteSequence(null);
    writer.writeToSequence(new IIOImage(frame1, null, null), param);
    writer.writeToSequence(new IIOImage(frame2, null, null), param);
    writer.endWriteSequence();
    writer.reset();
    writer.dispose();

    ios.flush();
    ios.close();

    return Toolkit.getDefaultToolkit().createImage("lut_test.gif");
}
 
Example 14
Source File: AnimationTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) {
    try {
        AnimationTest t = new AnimationTest();
        t.initFrame();

        ImageWriter w = t.initWriter();

        ImageWriteParam p = w.getDefaultWriteParam();

        IIOMetadata streamMetadata = w.getDefaultStreamMetadata(p);

        w.prepareWriteSequence(streamMetadata);

        for (int i = 0; i < 50; i++) {
            BufferedImage f = t.createNextFrame();

            ImageTypeSpecifier type = new ImageTypeSpecifier(f);

            IIOMetadata m = w.getDefaultImageMetadata(type, p);

            w.writeToSequence(new IIOImage(f, null, m), p);
        }
        w.endWriteSequence();

        t.checkAnimation();
    } catch (Exception e) {
        throw new RuntimeException("Test failed.", e);
    }
}
 
Example 15
Source File: AnimationTest.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) {
    try {
        AnimationTest t = new AnimationTest();
        t.initFrame();

        ImageWriter w = t.initWriter();

        ImageWriteParam p = w.getDefaultWriteParam();

        IIOMetadata streamMetadata = w.getDefaultStreamMetadata(p);

        w.prepareWriteSequence(streamMetadata);

        for (int i = 0; i < 50; i++) {
            BufferedImage f = t.createNextFrame();

            ImageTypeSpecifier type = new ImageTypeSpecifier(f);

            IIOMetadata m = w.getDefaultImageMetadata(type, p);

            w.writeToSequence(new IIOImage(f, null, m), p);
        }
        w.endWriteSequence();

        t.checkAnimation();
    } catch (Exception e) {
        throw new RuntimeException("Test failed.", e);
    }
}
 
Example 16
Source File: AnimatedGifExport.java    From snap-desktop with GNU General Public License v3.0 5 votes vote down vote up
private void exportAnimation(String delayTime, File file, ProgressMonitor pm) {

        ImageWriter imageWriter = ImageIO.getImageWritersByFormatName("gif").next();

        try {
            ImageOutputStream outputStream = ImageIO.createImageOutputStream(file);
            imageWriter.setOutput(outputStream);
            imageWriter.prepareWriteSequence(null);

            pm.beginTask("Exporting time series as animated gif", frames.length);

            for (int i = 0; i < frames.length; i++) {
                RenderedImage currentImage = frames[i];
                ImageWriteParam writeParameters = imageWriter.getDefaultWriteParam();
                IIOMetadata metadata = imageWriter.getDefaultImageMetadata(new ImageTypeSpecifier(currentImage),
                                                                           writeParameters);

                configure(metadata, delayTime, i);
                IIOImage image = new IIOImage(currentImage, null, metadata);
                imageWriter.writeToSequence(image, null);
                pm.worked(1);
            }
            imageWriter.endWriteSequence();
            outputStream.close();
            pm.done();
        } catch (IOException e) {
            SnapApp.getDefault().handleError("Unable to create animated gif", e);
        }
    }
 
Example 17
Source File: WriteToSequenceAfterAbort.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
private void test(final ImageWriter writer) throws IOException {
    String suffix = writer.getOriginatingProvider().getFileSuffixes()[0];

    // Image initialization
    BufferedImage imageUpperLeft =
            new BufferedImage(WIDTH, HEIGHT, TYPE_BYTE_BINARY);
    Graphics2D g = imageUpperLeft.createGraphics();
    g.setColor(Color.WHITE);
    g.fillRect(0, 0, WIDTH/2, HEIGHT/2);
    g.dispose();
    BufferedImage imageLowerRight =
            new BufferedImage(WIDTH, HEIGHT, TYPE_BYTE_BINARY);
    g = imageLowerRight.createGraphics();
    g.setColor(Color.WHITE);
    g.fillRect(WIDTH/2, HEIGHT/2, WIDTH/2, HEIGHT/2);
    g.dispose();
    TiledImage[] images = new TiledImage[] {
        new TiledImage(imageUpperLeft, NUM_TILES_XY, NUM_TILES_XY),
        new TiledImage(imageUpperLeft, NUM_TILES_XY, NUM_TILES_XY),
        new TiledImage(imageLowerRight, NUM_TILES_XY, NUM_TILES_XY),
        new TiledImage(imageLowerRight, NUM_TILES_XY, NUM_TILES_XY)
    };

    // File initialization
    File file = File.createTempFile("temp", "." + suffix);
    file.deleteOnExit();
    FileOutputStream fos = new SkipWriteOnAbortOutputStream(file);
    ImageOutputStream ios = ImageIO.createImageOutputStream(fos);
    writer.setOutput(ios);
    writer.addIIOWriteProgressListener(this);

    writer.prepareWriteSequence(null);
    boolean[] abortions = new boolean[] {true, false, true, false};
    for (int i = 0; i < 4; i++) {
        abortFlag = abortions[i];
        isAbortCalled = false;
        isCompleteCalled = false;
        isProgressCalled = false;
        isStartedCalled = false;

        TiledImage image = images[i];
        if (abortFlag) {
            // This write will be aborted, and file will not be touched
            writer.writeToSequence(new IIOImage(image, null, null), null);
            if (!isStartedCalled) {
                throw new RuntimeException("Started should be called");
            }
            if (!isProgressCalled) {
                throw new RuntimeException("Progress should be called");
            }
            if (!isAbortCalled) {
                throw new RuntimeException("Abort should be called");
            }
            if (isCompleteCalled) {
                throw new RuntimeException("Complete should not be called");
            }
        } else {
            // This write should be completed successfully and the file should
            // contain correct image data.
            writer.writeToSequence(new IIOImage(image, null, null), null);
            if (!isStartedCalled) {
                throw new RuntimeException("Started should be called");
            }
            if (!isProgressCalled) {
                throw new RuntimeException("Progress should be called");
            }
            if (isAbortCalled) {
                throw new RuntimeException("Abort should not be called");
            }
            if (!isCompleteCalled) {
                throw new RuntimeException("Complete should be called");
            }
        }
    }

    writer.endWriteSequence();
    writer.dispose();
    ios.close();

    // Validates content of the file.
    ImageReader reader = ImageIO.getImageReader(writer);
    ImageInputStream iis = ImageIO.createImageInputStream(file);
    reader.setInput(iis);
    for (int i = 0; i < 2; i++) {
        System.out.println("Testing image " + i);
        BufferedImage imageRead = reader.read(i);
        BufferedImage imageWrite = images[2 * i].getAsBufferedImage();
        for (int x = 0; x < WIDTH; ++x) {
            for (int y = 0; y < HEIGHT; ++y) {
                if (imageRead.getRGB(x, y) != imageWrite.getRGB(x, y)) {
                    throw new RuntimeException("Test failed for image " + i);
                }
            }
        }
    }
}
 
Example 18
Source File: Utils.java    From lizzie with GNU General Public License v3.0 4 votes vote down vote up
public static void toGif(
    String path, List<BufferedImage> frames, int delayTime, boolean override) {
  if (Utils.isBlank(path) || frames == null || frames.size() == 0) return;
  Iterator<ImageWriter> it = ImageIO.getImageWritersByFormatName("gif");
  try {
    File file = new File(path);
    if (override) {
      file.deleteOnExit();
    }

    ImageWriter writer = it.hasNext() ? it.next() : null;
    ImageOutputStream stream = ImageIO.createImageOutputStream(file);
    if (Objects.isNull(writer)) {
      throw new IOException();
    }
    writer.setOutput(stream);
    writer.prepareWriteSequence(null);

    IIOMetadataNode gce = new IIOMetadataNode("GraphicControlExtension");
    gce.setAttribute("disposalMethod", "none");
    gce.setAttribute("userInputFlag", "FALSE");
    gce.setAttribute("transparentColorFlag", "FALSE");
    gce.setAttribute("transparentColorIndex", "0");
    gce.setAttribute("delayTime", Objects.toString(delayTime));

    IIOMetadataNode ae = new IIOMetadataNode("ApplicationExtension");
    ae.setAttribute("applicationID", "NETSCAPE");
    ae.setAttribute("authenticationCode", "2.0");
    ae.setUserObject(new byte[] {0x1, 0x0, 0x0});

    IIOMetadataNode aes = new IIOMetadataNode("ApplicationExtensions");
    aes.appendChild(ae);

    for (BufferedImage image : frames) {
      ImageWriteParam iwp = writer.getDefaultWriteParam();
      IIOMetadata metadata = writer.getDefaultImageMetadata(new ImageTypeSpecifier(image), iwp);
      String metaFormat = metadata.getNativeMetadataFormatName();
      Node root = metadata.getAsTree(metaFormat);
      root.appendChild(gce);
      root.appendChild(aes);
      metadata.setFromTree(metaFormat, root);
      writer.writeToSequence(new IIOImage(image, null, metadata), null);
      metadata = null;
    }
    writer.endWriteSequence();
    stream.close();
  } catch (IOException ex) {
    ex.printStackTrace();
  }
}
 
Example 19
Source File: GifSequenceWriter.java    From scrimage with Apache License 2.0 4 votes vote down vote up
public byte[] bytes(ImmutableImage[] images) throws IOException {

        ImageWriter writer = ImageIO.getImageWritersBySuffix("gif").next();
        ImageWriteParam imageWriteParam = writer.getDefaultWriteParam();

        ImageTypeSpecifier imageTypeSpecifier = ImageTypeSpecifier.createFromBufferedImageType(images[0].awt().getType());
        IIOMetadata imageMetaData = writer.getDefaultImageMetadata(imageTypeSpecifier, imageWriteParam);

        String metaFormatName = imageMetaData.getNativeMetadataFormatName();

        IIOMetadataNode root = (IIOMetadataNode) imageMetaData.getAsTree(metaFormatName);

        IIOMetadataNode graphicsControlExtensionNode = getNode(root, "GraphicControlExtension");

        graphicsControlExtensionNode.setAttribute("disposalMethod", "none");
        graphicsControlExtensionNode.setAttribute("userInputFlag", "FALSE");
        graphicsControlExtensionNode.setAttribute("transparentColorFlag", "FALSE");
        graphicsControlExtensionNode.setAttribute("delayTime", (frameDelayMillis / 10) + "");
        graphicsControlExtensionNode.setAttribute("transparentColorIndex", "0");

        IIOMetadataNode commentsNode = getNode(root, "CommentExtensions");
        commentsNode.setAttribute("CommentExtension", "Created by Scrimage");

        IIOMetadataNode appEntensionsNode = getNode(root, "ApplicationExtensions");
        IIOMetadataNode child = new IIOMetadataNode("ApplicationExtension");

        child.setAttribute("applicationID", "NETSCAPE");
        child.setAttribute("authenticationCode", "2.0");

        int loop;
        if (infiniteLoop)
            loop = 0;
        else
            loop = 1;

        child.setUserObject(new byte[]{0x1, (byte) (loop & 0xFF), (byte) ((loop >> 8) & 0xFF)});
        appEntensionsNode.appendChild(child);

        imageMetaData.setFromTree(metaFormatName, root);

        try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
            try (MemoryCacheImageOutputStream output = new MemoryCacheImageOutputStream(baos)) {

                writer.setOutput(output);
                writer.prepareWriteSequence(null);

                for (ImmutableImage image : images) {
                    writer.writeToSequence(new IIOImage(image.awt(), null, imageMetaData), imageWriteParam);
                }

                writer.endWriteSequence();
                output.flush();
                return baos.toByteArray();
            }
        }
    }
 
Example 20
Source File: AnimatedGifUtil.java    From ChatGameFontificator with The Unlicense 4 votes vote down vote up
/**
 * Fix (ditto) for Java's animated GIF interpretation
 * 
 * Adapted from http://stackoverflow.com/questions/26801433/fix-frame-rate-of-animated-gif-in-java#answer-26829534
 * 
 * @param url
 *            The URL for the animated GIF to be loaded
 * @param dim
 *            The dimension object to be filled by the width and height of the loaded animated GIF
 * @return The loaded animated GIF
 * @throws Exception
 */
public static Image loadDittoAnimatedGif(final URL url, Dimension dim)
{
    final Image dimImage = new ImageIcon(url).getImage();

    Image image = null;
    try
    {
        ImageReader gifReader = ImageIO.getImageReadersByFormatName(GIF_EXTENSION).next();
        InputStream imageStream = url.openStream();
        gifReader.setInput(ImageIO.createImageInputStream(imageStream));
        IIOMetadata imageMetaData = gifReader.getImageMetadata(0);
        String metaFormatName = imageMetaData.getNativeMetadataFormatName();
        final int frameCount = gifReader.getNumImages(true);

        ByteArrayOutputStream baoStream = new ByteArrayOutputStream();
        ImageOutputStream ios = ImageIO.createImageOutputStream(baoStream);
        ImageWriter writer = ImageIO.getImageWriter(gifReader);
        writer.setOutput(ios);
        writer.prepareWriteSequence(null);

        final int imgWidth = dimImage.getWidth(null);
        final int imgHeight = dimImage.getHeight(null);
        dim.setSize(imgWidth, imgHeight);

        for (int i = 0; i < frameCount; i++)
        {
            // This read method takes into account the frame's top and left coordinates
            BufferedImage frame = gifReader.read(i);
            IIOMetadataNode nodes = (IIOMetadataNode) gifReader.getImageMetadata(i).getAsTree(metaFormatName);

            for (int j = 0; j < nodes.getLength(); j++)
            {
                IIOMetadataNode node = (IIOMetadataNode) nodes.item(j);
                if (GRAPHIC_CTRL_EXT.equalsIgnoreCase(node.getNodeName()))
                {
                    int delay = Integer.parseInt(node.getAttribute(ATTRIBUTE_DELAY_TIME));
                    // Minimum delay for browsers, which delay animated GIFs much more than would be to spec
                    if (delay < MIN_ANI_GIF_DELAY)
                    {
                        node.setAttribute(ATTRIBUTE_DELAY_TIME, Integer.toString(MIN_ANI_GIF_DELAY));
                    }
                    // Java's interpretation of restore to previous doesn't seem to work correctly, 
                    // at least not for BTTV's (ditto)
                    if (node.getAttribute(ATTRIBUTE_DISPOSAL_METHOD).equals(DISPOSE_RESTORE_TO_PREVIOUS))
                    {
                        node.setAttribute(ATTRIBUTE_DISPOSAL_METHOD, DISPOSE_RESTORE_TO_BGCOLOR);
                    }
                }
            }

            IIOMetadata metadata = writer.getDefaultImageMetadata(new ImageTypeSpecifier(frame), null);
            metadata.setFromTree(metadata.getNativeMetadataFormatName(), nodes);

            // This modified frame is necessary to get the correct image placement, width, and height in the final GIF
            BufferedImage frameMod = new BufferedImage(imgWidth, imgHeight, BufferedImage.TYPE_INT_ARGB);
            Graphics big = frameMod.getGraphics();
            big.drawImage(frame, 0, 0, null);

            IIOImage fixedFrame = new IIOImage(frameMod, null, metadata);
            writer.writeToSequence(fixedFrame, writer.getDefaultWriteParam());
        }
        writer.endWriteSequence();

        if (ios != null)
        {
            ios.close();
        }

        image = Toolkit.getDefaultToolkit().createImage(baoStream.toByteArray());
    }
    catch (Exception e)
    {
        // If anything goes wrong, just load it normally
        logger.error("Error loading animated GIF (ditto) from " + url, e);
        image = new ImageIcon(url).getImage();
        dim.setSize(image.getWidth(null), image.getHeight(null));
    }

    return image;
}