Method for php to judge whether GIF picture is animation

  • 2021-07-07 06:44:40
  • OfStack

This paper introduces the method of PHP judging that GIF pictures are animations. The specific steps are as follows:

First, the gif animation is in gif89 format, and it is found that the file begins with gif89. But many transparent pictures are also in gif89 format.

GOOGLE to: You can check whether the file contains: chr (0 × 21). chr (0xff). chr (0 × 0b). 'NETSCAPE 2.0'

chr (0 × 21). chr (0xff) is the header of the extended function section in the gif picture, and 'NETSCAPE2.0' is the program name of the extended function execution

The program code is as follows:


<?php
function check($image){
$content= file_get_contents($image);
if(preg_match("/".chr(0x21).chr(0xff).chr(0x0b).'NETSCAPE2.0'."/",$content)){ 
return true;
}else{
return false;
}
}
if(check('/home/lyy/luoyinyou/2.gif')){
echo' Really animated ';
}else{
echo' Not animation ';
}
?>

This code can still be optimized again:

In fact, chr (0 × 21). chr (0xff). chr (0 × 0b). 'NETSCAPE2.0' only appears in the head of the file, which can be seen by echo, but not the most head, but in a certain position of the head. Therefore, strictly speaking, it is necessary to read 1 part of the file, but not all of it, which can speed up and save memory.

The program can be rewritten as follows:


function check_animation($image_file){
$fp = fopen($image_file, 'rb');
$image_head = fread($fp,1024);
fclose($fp);
return preg_match("/".chr(0x21).chr(0xff).chr(0x0b).'NETSCAPE2.0'."/",$image_head) ? true : false;
}

The test found that 1024 bytes was enough to read, because the read data stream just contained chr (0 × 21). chr (0xff). chr (0 × 0b). 'NETSCAPE 2.0'

Supplements from other netizens


<?php
function IsAnimatedGif($filename)
{
	$fp = fopen($filename, 'rb');
	$filecontent = fread($fp, filesize($filename));
	fclose($fp);
	return strpos($filecontent,chr(0x21).chr(0xff).chr(0x0b).'NETSCAPE2.0') === FALSE?0:1;
}
echo IsAnimatedGif("51windows.gif");
?>

Related articles: