读取动画GIF中帧之间的延迟

时间:2013-11-19 17:21:26

标签: java image image-processing metadata animated-gif

如何阅读每帧之间动画GIF的控制块?我对每帧之间的延迟感兴趣。我看过ImageReader的Javadoc,我什么也没看到。

这是我用于从动画GIF中读取所有帧的代码,如何增强它以读取有关动画GIF中嵌入的每个帧的元数据?

    List<BufferedImage> list = new ArrayList<BufferedImage>();
    try {
        ImageReader reader = ImageIO.getImageReadersBySuffix("gif").next();
        reader.setInput(ImageIO.createImageInputStream(urlImage.openStream()));
        int i = reader.getMinIndex();
        int numImages = reader.getNumImages(true);
        while (i < numImages)
        {
            list.add(reader.read(i++));
        }

        // do stuff with frames of image...

    } catch (Exception e) {
        e.printStackTrace();
    }

1 个答案:

答案 0 :(得分:4)

您必须从元数据节点中寻找"delayTime"属性。使用以下工作示例来理解:

public class GiffTest {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws IOException {
        ImageReader reader = ImageIO.getImageReadersBySuffix("gif").next();
        reader.setInput(ImageIO.createImageInputStream(new FileInputStream("H:\\toonGif.gif")));
        int i = reader.getMinIndex();
        int numImages = reader.getNumImages(true);

        IIOMetadata imageMetaData =  reader.getImageMetadata(0);
        String metaFormatName = imageMetaData.getNativeMetadataFormatName();

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

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

        System.out.println(graphicsControlExtensionNode.getAttribute("delayTime"));
    }

    private static IIOMetadataNode getNode(IIOMetadataNode rootNode, String nodeName) {
        int nNodes = rootNode.getLength();
        for (int i = 0; i < nNodes; i++) {
            if (rootNode.item(i).getNodeName().compareToIgnoreCase(nodeName)== 0) {
            return((IIOMetadataNode) rootNode.item(i));
            }
       }
        IIOMetadataNode node = new IIOMetadataNode(nodeName);
        rootNode.appendChild(node);
        return(node);
  }
}