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

Spread your code soluces to the world

Love me
Solucior » PHP GD IMAGE » Adjust the rate of image colors

Adjust the rate of image colors

05/25/2011 by Dux   -   2/5 (1 ratings)

This script adjusts the amount of colors in a jpg, gif or png picture. By modifying the value $variant between -25 and 15, you get a picture more or less colorful.

Original picture

See a demonstration of this script in action :

Open in a new window     Open in the same window

source code

('memory_limit', '128M');

// Set the amount of effect ( -25 to 15 )
$variant = 5;

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

// 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);

if (
$variant<0) { $variant=$variant/$multiple; } else { $variant=$variant*$multiple; }
$quant= ($variant/70) +1;

// Create a bigger image for working with 256 colors
imagecopyresampled($img, $img2, 0, 0, 0, 0, $x*$multiple, $y*$multiple, $x, $y);

// calculating and modification in palette color
imagetruecolortopalette($img, true, 256);
$i=0; $i<imagecolorstotal( $img ); $i++ ) {
$c = ImageColorsForIndex( $img, $i );
$r=$c['red']; $v=$c['green']; $b=$c['blue'];
   if (
$r>$v && $r>$b) { $r=$r*$quant; $v=$v/$quant; $b=$b/$quant; }
   if (
$v>$r && $v>$b) { $r=$r/$quant; $v=$v*$quant; $b=$b/$quant; }
   if (
$b>$v && $b>$r) { $r=$r/$quant; $v=$v/$quant; $b=$b*$quant; }
   if (
$r>255) $r=255;
   if (
$v>255) $v=255;
   if (
$b>255) $b=255;
imagecolorset( $img, $i, $r, $v, $b );

// Back to original size with resample
imagecopyresampled($img2, $img, 0, 0, 0, 0, $x, $y, $x*$multiple, $y*$multiple);

// Now you can use $img to display or save it
Rate this code     |     Copied : 10x

Comments for Adjust the rate of image colors

No comment
Add a comment Nickname   Site

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