PHP 簡單檢查圖片是黑白還是彩色


下面 PHP 中的 0.05 這個數字看需求來調整.
目前測試的圖片是否黑白還是彩色都算是正常.記錄.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
<?php
/*\
* Usage: php detect-color.php /Users/zeuxis/Desktop/black-and-white.png
\*/
$image_path = $argv[1];

list($width, $height, $type, $attriable) = getimagesize($image_path);

$image = imagecreatefrompng($image_path);
$colorful = $black_white = 0;
$saturation = function($r, $g, $b) {
$r = ($r / 255);
$g = ($g / 255);
$b = ($b / 255);

$min = min($r, $g, $b);
$max = max($r, $g, $b);
$low = $max - $min;

return $low === 0 ? 0 : $low / $max;
};

for($i=0; $i<$width; $i++) {
for($j=0; $j<$height; $j++) {
$rgb = imagecolorat($image, $i, $j);
$red = ($rgb >> 16) & 0xFF;
$green = ($rgb >> 8) & 0xFF;
$blue = $rgb & 0xFF;
if ($saturation($red, $green, $blue)*250 < 40) {
$black_white++;
}else{
$colorful++;
}
}
}

echo ($colorful/$black_white > 0.05) ? "colorful" : "black and white";
echo "\n";
?>