PHP: Computing the different color count of a palletized image using GD

PHP: Calculando el número de apariciones de un color en una imagen paletizada usando GD

May 05 2009

$i  = imagecreate(1000, 1000);  
$c1 = imagecolorallocate($i, 0x00, 0x00, 0x00);  
$c2 = imagecolorallocate($i, 0xFF, 0xFF, 0xFF);  

imagefill($i, 0, 0, $c2);  

for ($n = 0; $n < 100; $n++) imagesetpixel($i, $n, $n, $c1);  

printf("Method1 (iterating using php) {\n");  
{  
    $t0 = microtime(true);  
    ob_start(); imagegd($i); $data = substr(ob_get_clean(), 0x40D);  
    printf("  Output image: %.4f seconds\n", microtime(true) - $t0);  

    $t0 = microtime(true);  
    $count = array();  
    list($w, $h) = array(imageSX($i), imageSY($i));  
    for ($y = 0; $y < $h; $y++) {  
        for ($x = 0; $x < $w; $x++) {  
            @$count[imagecolorat($i, $x, $y)]++;  
        }  
    }  
    $count = count_chars($data, 1);  
    arsort($count);  
    printf("  Counting: %.4f seconds\n", microtime(true) - $t0);  
    print_r($count);  
}  
printf("}\n");  

printf("Method2 (hack) {\n");  
{  
    $t0 = microtime(true);  
    ob_start(); imagegd($i); $data = substr(ob_get_clean(), 0x40D);  
    printf("  Output image: %.4f seconds\n", microtime(true) - $t0);  

    $t0 = microtime(true);  
    $count = count_chars($data, 1);  
    arsort($count);  
    printf("  Counting: %.4f seconds\n", microtime(true) - $t0);  
    print_r($count);  
}  
printf("}\n");