Pyh.conf’25: a new PHP conference for the Russian-speaking community

Voting

: four minus zero?
(Example: nine)

The Note You're Voting On

moxley at moxleydata dot com
18 years ago
I wanted to find out if a GIF is Black & White or Color, but I didn't want to wait around for imagecreatefromgif() to parse a 200k file (about 1 second) to get the color map, so I wrote this function to get a list of all the colors in the GIF. Hope it is useful for you.

<?php
function getGIFColorMap($file)
{
$fp = fopen($file, 'r');
$buf = fread($fp, 1024);
fclose($fp);

// Calculate number of colors
// buf[10] is the color info byte
$color_byte = ord($buf[10]);
$has_color_map = ($color_byte >> 7) & 1;
$color_res = (($color_byte >> 4) & 7) + 1;
$bits_per_pixel = ($color_byte & 7) + 1;
$color_count = 1 << $bits_per_pixel;

if (!
$has_color_map) return null;

// buf[13] is the beginning of the color map
$color_map_index = 13;
$map = array();
for (
$i=0; $i < $color_count; $i++) {
$index = $color_map_index + $i*3;
$r = ord($buf[$index]);
$g = ord($buf[$index + 1]);
$b = ord($buf[$index + 2]);
$map[$i] = array($r, $g, $b);
}
return
$map;
}
?>

<< Back to user notes page

To Top