Detecting an animated GIF in PHP

Following function detects if the GIF contains an animation (it has more than 1 frame) or is just a static file.

  function isAnimatedGif($filename)
  {
    $filecontents=file_get_contents($filename);
 
    $str_loc=0;
    $count=0;
 
    // There is no point in continuing after we find a 2nd frame
    while ($count < 2) 
    {
      $where1=strpos($filecontents,"\x00\x21\xF9\x04", $str_loc);
      if ($where1 === FALSE) {
        break;
      }
 
      $str_loc = $where1+1;
      $where2  = strpos($filecontents,"\x00\x2C",$str_loc);
      if ($where2 === FALSE) {
        break;
      }
      else {
        if ($where1+8 == $where2) {
          $count++;
        }
        $str_loc = $where2+1;
      }
    }
 
    // gif is animated when it has two or more frames
    return ($count >= 2); 
  }

Following function does the same but in a more compact way:

function isAnimatedGif($filename) {
    return (bool)preg_match('#(\x00\x21\xF9\x04.{4}\x00\x2C.*){2,}#s', file_get_contents($filename));
}

I have modified slightly the first function, but both of them come originally from the comments at http://es2.php.net/manual/en/function.imagecreatefromgif.php

Trackback URL

, ,

9 Comments on "Detecting an animated GIF in PHP"

Hi Stranger, leave a comment:

ALLOWED XHTML TAGS:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">

Subscribe to Comments