Here is a function that takes an image ($im) and returns it with the contrast maximised...
<?php
function contrast($im) {
$brightness=0;
$maxb=0;
$minb=255;
$imagesize=getimagesize($im);
$w=$imagesize[0];
$h=$imagesize[1];
for ($x=0; $x<$w; $x++) {
for ($y=0; $y<$h; $y++) {
$rgb=imagecolorat($im, $x, $y);
$rgb=imagecolorsforindex($im, $rgb);
$grey=0.2125*$rgb['red']+
0.7154*$rgb['green']+
0.0721*$rgb['blue'];
$brightness+=$grey;
if ($grey>$maxb) $maxb=$grey;
if ($grey<$minb) $minb=$grey;
}
}
$brightness=$brightness/($w*$h);
$minb=$brightness/($brightness-$minb);
$maxb=(255-$brightness)/($maxb-$brightness);
$contrast=min($minb, $maxb);
for ($x=0; $x<$w; $x++) {
for ($y=0; $y<$h; $y++) {
$rgb=imagecolorat($im, $x, $y);
$rgb=imagecolorsforindex($im, $rgb);
imagesetpixel($im, $x, $y,
65536*floor(min($rgb['red']*$contrast, 255))+
256*floor(min($rgb['green']*$contrast, 255))+
floor(min($rgb['blue']*$contrast, 255)));
}
}
return ($im);
}
?>
An example of usage might be:
<?php
$imagefile="/path/filename";
$image=imagecreatefromjpeg($imagefile);
$image=contrast($image);
imagejpeg($image, $imagefile);
?>