How to get the length (in time) from an animated GIF

Is there any way to find out how long an animated GIF will take with one loop?

+4
source share
2 answers

Well, sortaโ€™s specifics depend on which interface you use to manage these animated GIFs (I donโ€™t know the real slippery way in native Java / AWT / Swing), but the main idea would be to calculate (frame speed * number of frames).

If you manually code the GIF manipulation tool, I recommend taking a look at http://www.onicos.com/staff/iz/formats/gif.html

Hope this helps at least a little.

Update. Try implementing the ImageObserver interface. Take a look at the ImageObserver.FRAMEBITS flag in this class to detect frame updates. http://docs.oracle.com/javase/6/docs/api/java/awt/image/ImageObserver.html

This still leaves the question of how many frames the gif has. You can try to take a look at the Image.getProperty () function. I find it difficult to find documentation on whether there is a "frame" property, but look.

+1
source

Use the Metadata-Extractor library to read the meta-information of image files. This piece of code can be used to read the GifControlDirectory for each image (frame) in the GIF file.

/** * Get time length of GIF file in milliseconds. * * @return time length of gif in ms. */ public int getGifAnimatedTimeLength(String imagePath) { Metadata metadata = ImageMetadataReader.readMetadata(imagePath); List<GifControlDirectory> gifControlDirectories = (List<GifControlDirectory>) metadata.getDirectoriesOfType(GifControlDirectory.class); int timeLength = 0; if (gifControlDirectories.size() == 1) { // Do not read delay of static GIF files with single frame. } else if (gifControlDirectories.size() >= 1) { for (GifControlDirectory gifControlDirectory : gifControlDirectories) { try { if (gifControlDirectory.hasTagName(GifControlDirectory.TAG_DELAY)) { timeLength += gifControlDirectory.getInt(GifControlDirectory.TAG_DELAY); } } catch (MetadataException e) { e.printStackTrace(); } } // Unit of time is 10 milliseconds in GIF. timeLength *= 10; } return timeLength; } 

Please note that even if the GIF file has several frames, it is possible that each frame may have a delay of 0 or without TAG_DELAY metadata. In addition, this article describes another problem of how different platforms use the delay value.

+1
source

Source: https://habr.com/ru/post/1384201/


All Articles