Created
August 9, 2015 17:34
-
-
Save mugifly/d9e47eb164a4dcc43ab8 to your computer and use it in GitHub Desktop.
Detector for animated GIF image (perl5)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env perl | |
# Detector for animated GIF image (perl5) | |
# Based on http://d.hatena.ne.jp/namanamanamana/20090415/1239729068 Thanks. | |
use strict; | |
use warnings; | |
use LWP::UserAgent; | |
# Fetch a GIF image | |
my $ua = LWP::UserAgent->new(); | |
my $res = $ua->get('http://example.com/foo-animation.gif'); | |
print "Fetch status = " . $res->status_line . "\n"; | |
# Check the file | |
my $fh; | |
open($fh, '<', $res->content_ref); # Or you can also read a file from local with the open method. | |
if (is_anim_gif_file($fh)) { | |
print "This is an animated GIF image.\n"; | |
} else { | |
print "This is not an animated GIF image.\n"; | |
} | |
close($fh); | |
exit; | |
sub is_anim_gif_file { | |
my $fh = shift; | |
my ($frame_num, $c) = (0, undef); | |
read($fh, $c, 4); | |
$c = undef; | |
# Check a GIF89 identifier | |
read($fh, $c, 1); | |
if (unpack("H*", $c) ne "39") { | |
return 0; | |
} | |
$c = undef; | |
# Read frames | |
while (!eof $fh) { | |
# Read until start point of extended block | |
do { | |
$c = undef; | |
read($fh, $c, 1); | |
} while (unpack("H*", $c) ne "21" && !eof $fh); | |
if (eof $fh) { | |
last; | |
} | |
# Read the Graphic Control Extension | |
$c = undef; | |
read($fh, $c, 2); | |
my $ext = unpack("H*", $c); | |
if ($ext eq "f904") { | |
$frame_num++; # Increment a number of frames | |
} | |
} | |
if ($frame_num <= 1){ | |
return 0; | |
} | |
return 1; # Animated GIF | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment