This is a (very) small part of PHPhoto. It generates a histogram for an image based on its R, G and B channels. Very simple stuff, but I figured I'd let you all pull it apart anyway:
<?php
$file = "file.jpg";
$source = imagecreatefromjpeg($file);
for ($x=0;$x<imagesx($source);$x++) {
for ($y=0;$y<imagesy($source);$y++) {
$rgb = imagecolorat($source,$x,$y);
$r = ($rgb >> 16) & 0xFF;
$g = ($rgb >> 8) & 0xFF;
$b = $rgb & 0xFF;
$r_total[$r]++;
$g_total[$g]++;
$b_total[$b]++;
$pixelcount++;
}
}
imagedestroy($source);
$r_range = (max($r_total)-min($r_total));
$g_range = (max($g_total)-min($g_total));
$b_range = (max($b_total)-min($b_total));
$histogram = imagecreatetruecolor(300,320);
$white = imagecolorallocate($histogram,255,255,255);
imagefilledrectangle($histogram,0,0,300,320,$white);
imagecolordeallocate($histogram,$white);
$black = imagecolorallocate($histogram,0,0,0);
for ($x=0;$x<256;$x++) {
imageline($histogram,($x+20),100,($x+20),(100-(($r_total[$x]/$r_range)*80)),$black);
imageline($histogram,($x+20),200,($x+20),(200-(($g_total[$x]/$g_range)*80)),$black);
imageline($histogram,($x+20),300,($x+20),(300-(($b_total[$x]/$b_range)*80)),$black);
}
imagestring($histogram,2,200,100,"Red Channel",$black);
imagestring($histogram,2,200,200,"Green Channel",$black);
imagestring($histogram,2,200,300,"Blue Channel",$black);
header("Content-Type: image/jpeg");
imageJPEG($histogram);
imagedestroy($histogram);
?>
Points to note:
- file.jpg is a jpg image in the same directory as the script. The image must be truecolour.
- imagecreateruecolor is a GD 2 function. This isn't going to work without that.
- Its damn ugly code. 😉