5 * Deliberately not using MWExceptions to avoid external dependencies, encouraging
9 class PNGMetadataExtractor
{
13 static function getMetadata( $filename ) {
14 self
::$png_sig = pack( "C8", 137, 80, 78, 71, 13, 10, 26, 10 );
22 throw new Exception( __METHOD__
. "No file name specified" );
23 elseif ( !file_exists($filename) ||
is_dir($filename) )
24 throw new Exception( __METHOD__
. "File $filename does not exist" );
26 $fh = fopen( $filename, 'r' );
29 throw new Exception( __METHOD__
. "Unable to open file $filename" );
31 // Check for the PNG header
32 $buf = fread( $fh, 8 );
33 if ( !($buf == self
::$png_sig) ) {
34 throw new Exception( __METHOD__
. "Not a valid PNG file; header: $buf" );
38 while( !feof( $fh ) ) {
39 $buf = fread( $fh, 4 );
40 if( !$buf ) { throw new Exception( __METHOD__
. "Read error" ); return; }
41 $chunk_size = unpack( "N", $buf);
42 $chunk_size = $chunk_size[1];
44 $chunk_type = fread( $fh, 4 );
45 if( !$chunk_type ) { throw new Exception( __METHOD__
. "Read error" ); return; }
47 if ( $chunk_type == "acTL" ) {
48 $buf = fread( $fh, $chunk_size );
49 if( !$buf ) { throw new Exception( __METHOD__
. "Read error" ); return; }
51 $actl = unpack( "Nframes/Nplays", $buf );
52 $frameCount = $actl['frames'];
53 $loopCount = $actl['plays'];
54 } elseif ( $chunk_type == "fcTL" ) {
55 $buf = fread( $fh, $chunk_size );
56 if( !$buf ) { throw new Exception( __METHOD__
. "Read error" ); return; }
57 $buf = substr( $buf, 20 );
59 $fctldur = unpack( "ndelay_num/ndelay_den", $buf );
60 if( $fctldur['delay_den'] == 0 ) $fctldur['delay_den'] = 100;
61 if( $fctldur['delay_num'] ) {
62 $duration +
= $fctldur['delay_num'] / $fctldur['delay_den'];
64 } elseif ( ( $chunk_type == "IDAT" ||
$chunk_type == "IEND" ) && $frameCount == 0 ) {
65 // Not a valid animated image. No point in continuing.
67 } elseif ( $chunk_type == "IEND" ) {
70 fseek( $fh, $chunk_size, SEEK_CUR
);
72 fseek( $fh, self
::$CRC_size, SEEK_CUR
);
76 if( $loopCount > 1 ) {
77 $duration *= $loopCount;
81 'frameCount' => $frameCount,
82 'loopCount' => $loopCount,
83 'duration' => $duration