colorcount.php
某ブログを書いてて、イメージ画像中の色数を数えたかったので作りました。
実行イメージ
% php colorcount.php tmp.png 255
プログラム
- colorcount.php
<?php if ($argc < 2) { echo "Usage: php colorcount.php <image_file>\n"; exit(1); } $im = imagecreatefromstring(file_get_contents($argv[1])); $width = imagesx($im); $height = imagesy($im); $colorcount = array(); for ($x = 0; $x < $width; $x++){ for ($y = 0; $y < $height; $y++){ $colorindex = imagecolorat($im, $x, $y); if (!isset($colorcount[$colorindex])){ $colorcount[$colorindex] = 1; } else{ $colorcount[$colorindex]++; } } } echo count($colorcount).PHP_EOL;