$target) { //we need to darken the photo $min = -4; $max = 0; } else { //we need to make it brighter $min = 0; $max = 4; } $i = 0; do { $current = ($min + $max) / 2; $brightness = adjust($current, $file); $diff = $target - $brightness; echo "Current value: $current\n"; echo "Current brightness: $brightness\n"; echo "Current diff: $diff\n"; if($diff > 0) { //we need to make it lighter $min = $current; } else { //we need to make it darker $max = $current; } $i++; } while(abs($diff) > 200); //overwrite original image with adjusted tmpfile unlink($file); rename($tmpfile,$file); } function adjust($value, $file) { global $tmpfile; @unlink($tmpfile); if($value > 0) { shell_exec("convert $file -sigmoidal-contrast '$value,0%' $tmpfile"); } else { shell_exec("convert $file +sigmoidal-contrast '$value,0%' $tmpfile"); } $out = shell_exec("identify -format \"%[mean]\" $tmpfile"); return floatval($out); }