<?php
function getColorStatistics($histogramElements, $colorChannel) {
$colorStatistics = [];
foreach ($histogramElements as $histogramElement) {
$color = $histogramElement->getColorValue($colorChannel);
$color = intval($color * 255);
$count = $histogramElement->getColorCount();
if (array_key_exists($color, $colorStatistics)) {
$colorStatistics[$color] += $count;
}
else {
$colorStatistics[$color] = $count;
}
}
ksort($colorStatistics);
return $colorStatistics;
}
function getImageHistogram($imagePath) {
$backgroundColor = 'black';
$draw = new \ImagickDraw();
$draw->setStrokeWidth(0); // Π΄Π΅Π»Π°Π΅Ρ Π»ΠΈΠ½ΠΈΠΈ ΠΌΠ°ΡΠΊΠΈΠΌΠ°Π»ΡΠ½ΠΎ ΡΠΎΠ½ΠΊΠΈΠΌΠΈ
$imagick = new \Imagick();
$imagick->newImage(500, 500, $backgroundColor);
$imagick->setImageFormat("png");
$imagick->drawImage($draw);
$histogramWidth = 256;
$histogramHeight = 100; // Π²ΡΡΠΎΡΠ° Π΄Π»Ρ ΠΊΠ°ΠΆΠ΄ΠΎΠ³ΠΎ ΡΠ΅Π³ΠΌΠ΅Π½ΡΠ° RGB
$imagick = new \Imagick(realpath($imagePath));
//ΠΠ·ΠΌΠ΅Π½ΠΈΡΠ΅ ΡΠ°Π·ΠΌΠ΅Ρ ΠΈΠ·ΠΎΠ±ΡΠ°ΠΆΠ΅Π½ΠΈΡ, ΡΡΠΎΠ±Ρ ΠΎΠ½ Π±ΡΠ» ΠΌΠ°Π»Π΅Π½ΡΠΊΠΈΠΌ, ΠΈΠ½Π°ΡΠ΅ PHP ΠΌΠΎΠΆΠ΅Ρ Π½Π΅ Ρ
Π²Π°ΡΠΈΡΡ ΠΏΠ°ΠΌΡΡΠΈ
//ΠΡΠΎ ΠΌΠΎΠΆΠ΅Ρ ΠΏΡΠΈΠ²Π΅ΡΡΠΈ ΠΊ ΠΏΠ»ΠΎΡ
ΠΈΠΌ ΡΠ΅Π·ΡΠ»ΡΡΠ°ΡΠ°ΠΌ Π΄Π»Ρ ΠΈΠ·ΠΎΠ±ΡΠ°ΠΆΠ΅Π½ΠΈΠΉ, ΠΊΠΎΡΠΎΡΡΠ΅ ΡΠ²Π»ΡΡΡΡΡ ΠΏΠ°ΡΠΎΠ»ΠΎΠ³ΠΈΡΠ΅ΡΠΊΠΈ "ΠΏΠΈΠΊΡΠ΅Π»ΡΠ½ΡΠΌΠΈ"
$imagick->adaptiveResizeImage(200, 200, true);
$histogramElements = $imagick->getImageHistogram();
$histogram = new \Imagick();
$histogram->newpseudoimage($histogramWidth, $histogramHeight * 3, 'xc:black');
$histogram->setImageFormat('png');
$getMax = function ($carry, $item) {
if ($item > $carry) {
return $item;
}
return $carry;
};
$colorValues = [
'red' => getColorStatistics($histogramElements, \Imagick::COLOR_RED),
'lime' => getColorStatistics($histogramElements, \Imagick::COLOR_GREEN),
'blue' => getColorStatistics($histogramElements, \Imagick::COLOR_BLUE),
];
$max = array_reduce($colorValues['red'] , $getMax, 0);
$max = array_reduce($colorValues['lime'] , $getMax, $max);
$max = array_reduce($colorValues['blue'] , $getMax, $max);
$scale = $histogramHeight / $max;
$count = 0;
foreach ($colorValues as $color => $values) {
$draw->setstrokecolor($color);
$offset = ($count + 1) * $histogramHeight;
foreach ($values as $index => $value) {
$draw->line($index, $offset, $index, $offset - ($value * $scale));
}
$count++;
}
$histogram->drawImage($draw);
header( "Content-Type: image/png" );
echo $histogram;
}
?>