PHP Snippets
image_contrast
Information
(PHP Version >= 4.0.6)Functions used in this snippet: imagesx, imagesy, imagecreatetruecolor, imagecolorat, min, floor, max, ceil, imagesetpixel, imagecolorallocate.
Description
int image_contrast( int img, int percent )
Adjusts the contrast of the image img based on the percent of percent. Percent is any number above 0. The lower the number, the darker the image will get. The higher the number, the brighter the image will get.
*Note: This function is fairly slow, so it would be best to apply the function once and save the image for further viewings.
You can view an example of this at Example of image_contrast
Snippet
<?php
function image_contrast($img, $percent){
$x = imagesx($img);
$y = imagesy($img);
$dest = imagecreatetruecolor($x, $y);
$percent = $percent / 100;
for($i=0; $i<$x; $i++){
for($j=0; $j<$y; $j++){
$rgb = imagecolorat($img, $i, $j);
$r = ($rgb >> 16) & 0xFF;
$g = ($rgb >> 8) & 0xFF;
$b = $rgb & 0xFF;
$r = $percent > 1 ? min(floor($r * $percent), 255) : max(ceil($r * $percent), 0);
$g = $percent > 1 ? min(floor($g * $percent), 255) : max(ceil($g * $percent), 0);
$b = $percent > 1 ? min(floor($b * $percent), 255) : max(ceil($b * $percent), 0);
imagesetpixel($dest, $i, $j, imagecolorallocate($dest, $r, $g, $b));
}
}
return $dest;
}
?>
Example
image_contrast Can be used in the following way:
<?php
$img = imagecreatefromjpeg('someimage.jpg'); // load an image
$dest = image_contrast($img, 50);
// decrease contrast by 50%
$dest = image_contrast($img, 150);
// increase contrast by 50%
header('Content-type: image/jpeg'); // set header
imagejpeg($dest); // send to browser
?>
Updated on Aug 3rd at 4 am.
0 Responses to image_contrast