19

Here is a link to another question I asked concerning the same project I am working on. I think that bit of background will be helpful.

For those that are too lazy to open a new tab to that question, I'll summarize what I'm trying to do here: I've downloaded about 250,000 images from 4scrape and I want to go through the GIFs and find which ones are animated or not. I need to do this programmatically, because I really don't feel my soul (or my relationship with my girlfriend) could use looking at a couple thousand GIFs from 4chan to see if they are animated or not. If you know the nature of 4chan, then you know the nature of the images (i.e. "tits or GTFO").

I know PHP and Python, but would be willing to explore other solutions. A stand-alone piece of software that works on Windows would also work.

Thanks a lot!

1

12 Answers 12

20

With Python and PIL:

from PIL import Image
gif = Image.open('path.gif')
try:
    gif.seek(1)
except EOFError:
    isanimated = False
else:
    isanimated = True
4
  • 1
    Thanks for this tip. Tiny nit: it might be important to seek the image back to 0, since gif.tell() will return 1 even in the except block, if I'm not mistaken.
    – Ben
    Oct 4, 2011 at 0:56
  • It's actually pretty easy with the function getIteratorIndex php.net/manual/en/imagick.getiteratorindex.php
    – arghav
    Mar 15, 2013 at 20:39
  • 1
    It's wrong. If the format of image file is MPO. The above example also workable.
    – Ryan Fau
    Jun 16, 2016 at 10:52
  • 5
    These days (Pillow==4.3.0) you can simply do from PIL import Image; Image.open('animated.gif').is_animated Dec 13, 2017 at 11:01
15

If you're on Linux (or any system with ImageMagick) you can use a one-liner shell script and identify program:

identify *.gif | fgrep '.gif[1] '

I know you said you prefer PHP and Python, but you also said you are willing to explore other solutions. :)

3
  • For other newbies: "fgrep - search a file for a fixed-string pattern" / "The fgrep command searches the input files specified by the File parameter (standard input by default) for lines that match a pattern." – Above we search for the occurence of string .gif[1]
    – Avatar
    Nov 14, 2022 at 7:03
  • 1
    Example output of identify static.gif: "static.gif GIF 599x1091 599x1091+0+0 8-bit sRGB 128c 180159B 0.000u 0:00.000". Example output of identify animated.gif: "animated.gif[0] GIF 425x319 425x319+0+0 8-bit sRGB 256c 0.000u 0:00.000" "animated.gif[1] GIF 425x319 425x319+0+0 8-bit sRGB 256c 0.000u 0:00.000" ← several lines
    – Avatar
    Nov 14, 2022 at 7:06
  • 2
    Alternative command on Linux/Ubuntu: identify -format %n giffile.gif – The %n gives the number of scenes, if more than one then its animated.
    – Avatar
    Nov 14, 2022 at 7:11
10

Pillow 2.9.0 added is_animated:

This adds the property is_animated, to check if an image has multiple layers or frames.

Example usage:

from PIL import Image
print(Image.open("test.gif").is_animated)
2
  • This applies only to a GIF. If I check it with another image (like JPEG), I get an exception.
    – Uri
    May 4, 2020 at 10:17
  • @Uri probably a bug that should be reported to developers.
    – qwr
    Jan 16, 2021 at 10:43
9

I've never seen a program that will tell you this. But GIF is a block structured format and you can check if the block indicating animated GIF is present in your files.

From wikipedia article noted below: at offset 0x30D an Application Extension (ie: 3 byte magic number 21 FF 0B) block in the GIF file, followed by magic number 4E 45 54 53 43 41 50 45 32 9at offset 0x310 indicates that the rest of the file contains multiple images, and they should be animated.

Really the Wikipedia article explains it better and the format docs noted below expand on the Wiki article.

So you can parse the GIFs using a program written in Python (I parsed GIFs using C many years ago, it was mainly an exercise in moving the file pointer around and reading bytes). Determine if the AE is present with the correct 3 byte ID, and followed by the 9 byte magic number.

See http://en.wikipedia.org/wiki/Graphics_Interchange_Format#Animated_.gif

Also see http://www.martinreddy.net/gfx/2d/GIF87a.txt

Also see http://www.martinreddy.net/gfx/2d/GIF89a.txt

Sorry, best I can do for you.

3

A few solutions are given on the PHP docs page for the imagecreatefromgif function.

From the solutions I've read, this one seems the best due to its tighter memory requirements.

<?php
function is_ani($filename) {
    if(!($fh = @fopen($filename, 'rb')))
        return false;
    $count = 0;
    //an animated gif contains multiple "frames", with each frame having a
    //header made up of:
    // * a static 4-byte sequence (\x00\x21\xF9\x04)
    // * 4 variable bytes
    // * a static 2-byte sequence (\x00\x2C)

    // We read through the file til we reach the end of the file, or we've found
    // at least 2 frame headers
    while(!feof($fh) && $count < 2) {
        $chunk = fread($fh, 1024 * 100); //read 100kb at a time
        $count += preg_match_all('#\x00\x21\xF9\x04.{4}\x00\x2C#s', $chunk, $matches);
    }
    fclose($fh);
    return $count > 1;
}
?>
2
  • WARNING! This snippet of code has a major bug in it. The while statement should include brackets, otherwise this function WILL NOT catch all animated gifs. Though it will catch some (which of couse is worse than it failing 100%). See the complete and fixed code at this stackoverflow url stackoverflow.com/questions/280658/… Nov 22, 2011 at 5:36
  • In fact, there is an even newer version of this script that fixes a bug potentially created by photoshop cs5 animated gifs. See it here Nov 22, 2011 at 5:41
2

Read the GIF89A specification and extract the information. http://www.w3.org/Graphics/GIF/spec-gif89a.txt

Or easy and lazy and ready for a hack use the intergif program which can extract the single images out of an animated gif. Extract into a temp directory and look how many files you get. http://utter.chaos.org.uk/~pdh/software/intergif/download.htm

2

I'm no GIF file format expert, but this is an interesting problem to me so I looked into it a bit. This would work only if it's always true that animated gifs have the value NETSCAPE2.0 at position 0x310 (edit)AND static gifs do not,(/edit) which was the case in my test files. This is C#, if you want I could compile it to a console app that takes a directory as an argument and you could run some test on your very large gif collection to see if it produces reliable results.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.IO;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            string ani = @"C:\path\to\ani.gif";
            string sta = @"C:\path\to\static.gif";

            Console.WriteLine(isAnimated(ani));
            Console.WriteLine(isAnimated(sta));
        }

        static bool isAnimated(string path)
        {
            byte[] bytes = File.ReadAllBytes(path);
            byte[] netscape = bytes.Skip(0x310).Take(11).ToArray();

            StringBuilder sb = new StringBuilder();

            foreach (var item in netscape)
            {
                sb.Append((char)item);
            }

            return sb.ToString() == "NETSCAPE2.0";
        }
    }
}
1
  • Not a complete check. While helpful does not work for all gifs.
    – Pat
    Aug 27, 2018 at 18:49
1

see if there is more than one LocalDescriptor are there in the GIF file.

1
  • 1
    Please expand your answer. This is more like a comment.
    – Lee Taylor
    Dec 21, 2012 at 1:00
1

The ImageMagick function getNumberImages will do this for you. Since it returns the number of images in the object. Imagick::getNumberImages

<?php

$image = new Imagick( YOUR_FILE );

if ( $image->getNumberImages() ) {
    echo "It's animated";
}
0

try this

import Image

def checkAnimate():
    im = Image.open('image.gif')
    if not im.info['version'].__contains__('GIF'):
        print "It's not a GIF file"
    else:
        if im.info.has_key('duration'):
            if im.info['duration'] > 0:
                return True
            else:
                return False
        else:
            return False
0
from PIL import Image
fp = open('1.gif', 'rb')
im = Image.open(fp)
is_gif = bool(im.format and im.format.upper() == 'GIF')
1
  • 1
    Although this code may answer the question, providing additional context regarding why and/or how it answers the question would significantly improve its long-term value. Please edit your answer to add some explanation. Apr 27, 2016 at 12:12
0

For the benefit of people who don't want to rely on a third party module like Pillow, here is an entirely python 2 and 3 native solution:

import sys
is_py2 = sys.version_info[0] == 2


def is_animated_gif(image_path):
    """Return true if image is an animated gif

    primarily used this great deep dive into the structure of an animated gif
    to figure out how to parse it:

        http://www.matthewflickinger.com/lab/whatsinagif/bits_and_bytes.asp

    Other links that also helped:

        https://en.wikipedia.org/wiki/GIF#Animated_GIF
        https://www.w3.org/Graphics/GIF/spec-gif89a.txt
        https://stackoverflow.com/a/1412644/5006

    :param image_path: string, assumed to be a path to a gif file
    :returns: boolean, True if the image is an animated gif
    """
    ret = False
    image_count = 0

    def skip_color_table(fp, packed_byte):
        """this will fp.seek() completely passed the color table"""
        if is_py2:
            packed_byte = int(packed_byte.encode("hex"), 16)

        has_gct = (packed_byte & 0b10000000) >> 7
        gct_size = packed_byte & 0b00000111

        if has_gct:
            global_color_table = fp.read(3 * pow(2, gct_size + 1))

    def skip_image_data(fp):
        """skips the image data, which is basically just a series of sub blocks
        with the addition of the lzw minimum code to decompress the file data"""
        lzw_minimum_code_size = fp.read(1)
        skip_sub_blocks(fp)

    def skip_sub_blocks(fp):
        """skips over the sub blocks

        the first byte of the sub block tells you how big that sub block is, then
        you read those, then read the next byte, which will tell you how big
        the next sub block is, you keep doing this until you get a sub block
        size of zero"""
        num_sub_blocks = ord(fp.read(1))
        while num_sub_blocks != 0x00:
            fp.read(num_sub_blocks)
            num_sub_blocks = ord(fp.read(1))

    with open(image_path, "rb") as fp:
        header = fp.read(6)
        if header == b"GIF89a": # GIF87a doesn't support animation
            logical_screen_descriptor = fp.read(7)
            skip_color_table(fp, logical_screen_descriptor[4])

            b = ord(fp.read(1))
            while b != 0x3B: # 3B is always the last byte in the gif
                if b == 0x21: # 21 is the extension block byte
                    b = ord(fp.read(1))
                    if b == 0xF9: # graphic control extension
                        block_size = ord(fp.read(1))
                        fp.read(block_size)
                        b = ord(fp.read(1))
                        if b != 0x00:
                            raise ValueError("GCT should end with 0x00")

                    elif b == 0xFF: # application extension
                        block_size = ord(fp.read(1))
                        fp.read(block_size)
                        skip_sub_blocks(fp)

                    elif b == 0x01: # plain text extension
                        block_size = ord(fp.read(1))
                        fp.read(block_size)
                        skip_sub_blocks(fp)

                    elif b == 0xFE: # comment extension
                        skip_sub_blocks(fp)

                elif b == 0x2C: # Image descriptor
                    # if we've seen more than one image it's animated
                    image_count += 1
                    if image_count > 1:
                        ret = True
                        break

                    # total size is 10 bytes, we already have the first byte so
                    # let's grab the other 9 bytes
                    image_descriptor = fp.read(9)
                    skip_color_table(fp, image_descriptor[-1])
                    skip_image_data(fp)

                b = ord(fp.read(1))

    return ret

The is_animated_gif() function works by skipping over all the extensions and color information and counting the actual images in the file, when it finds the second image it can safely assume the gif is animated and its work is done.

It doesn't rely on any shortcuts like checking for the existence of an application extension block because it didn't seem like those were required for the gif to be animated, and I didn't want to assume anything.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.