Code solutions to PHP, JS, CSSCode source PHP, JS, CSS

Spread your code soluces to the world

Love me
Solucior » PHP GD IMAGE » Automatically adjust brightness contrast of an image

Automatically adjust brightness contrast of an image

05/18/2011 by Dux   -   4.9/5 (7 ratings)

This script adjusts the brightness and contrast of an image using PHP5 and the GD2 library.
Set the variable $url_img with the path of your initial image. You can change the variable  which corresponds to the size of the working image of the script.

source code



 
<?php

// Size of the tempory image (according to the power of your server)
$taille_echant = 70;

// Path to the picture file
$url_img = 'picture.jpg';

// Detect format and create $img
$part = pathinfo($url_img);
$ext = strtolower($part['extension']);
if (
$ext == "jpg" or $ext == "jpeg") $img=imagecreatefromjpeg($url_img);
if (
$ext == "gif") $img=imagecreatefromgif($url_img);
if (
$ext == "png") $img=imagecreatefrompng($url_img);

// Image size
list($x,$y) = getimagesize($url_img);

// Create a smaller tempory image to prevent overloading the server
$img3 = imagecreatetruecolor($taille_echant,$taille_echant);
imagecopyresampled($img3, $img, 0, 0, 0, 0, $taille_echant, $taille_echant, $x, $y);

// Calcul max values of the black and white
$noir = 255;
for(
$x=0; $x < $taille_echant; $x=$x+1 ) {
 for(
$y=0; $y < $taille_echant; $y=$y+1 ) {
   
$color_index = imagecolorat($img3, $x, $y);
   
$c = ImageColorsForIndex( $img3, $color_index );
   
$t = ($c["red"]+$c["green"]+$c["blue"])/3;
   if (
$t<$noir) $noir = $t;
   if (
$t>$blanc) $blanc = $t;
 }
}
$blanc = 255 - $blanc;
 
if (
$noir > $blanc) {
 
// overex
 
imagefilter ($img, IMG_FILTER_CONTRAST, (-$noir+$blanc) / 10 );
 
imagefilter ($img, IMG_FILTER_BRIGHTNESS, (-$noir+$blanc) / 5);

} else {
 
// underex
 
imagefilter ($img, IMG_FILTER_CONTRAST, (-$blanc-$noir) / 10 );
 
imagefilter ($img, IMG_FILTER_BRIGHTNESS, ($blanc-$noir) / 6);
}


// Now you can display or save your image with $ img
 
?>
Rate this code     |     Copied : 101x

Comments for Automatically adjust brightness contrast of an image

No comment
Add a comment Nickname
ZOOM


Automatically adjust brightness contrast of an image
Isolate a color
Extract images from a page
Horizontal scroll div with javascript
Javascript Image magnification
Javascript opacity
Adjust the rate of image colors
Zoom with CSS3
Simple image gallery PHP
Dynamic image resizing according to location