Home Tutorial Php Phpgd PHP GD Replace Color

 
 

Share on Google+Share on Google+
PHP GD Replace Color
Posted on: November 10, 2009 at 12:00 AM
Advertisement
This example shows how to replace color of an image in php gd.

<?php

$image = "images.jpg";

$data = getimagesize($image);

$width = intval($data[0]);

$height = intval($data[1]);

$cloneH = 0;

$hex = "FF0000";

$oldhex = "FCFF00";

$im = imagecreatefromJPEG($image);

$color =

imagecolorallocate($im,hexdec(substr($hex,0,2)),hexdec(substr($hex,2,2)),hexdec(substr($hex,4,6)));

for($cloneH=0;$cloneH<$height;$cloneH++)

{

for($x=0;$x<$width;$x++)

{

if( colormatch($im,$x,$cloneH, $oldhex) )

imagesetpixel($im, $x, $cloneH, $color);

}

}

 

header("Content-Type: {$data['mime']}");

imageJPEG($im);

function colormatch($image,$x,$y,$hex)

{

$rgb = imagecolorat($image,$x,$y);

$r = ($rgb >> 16) & 0xFF;

$g = ($rgb >> 8) & 0xFF;

$b = $rgb & 0xFF;

 

$r2 = hexdec(substr($hex,0,2));

$g2 = hexdec(substr($hex,2,2));

$b2 = hexdec(substr($hex,4,6));

if( $r == $r2 && $b == $b2 && $g == $g2 )

return true;

return false;

}

?>

After running the program you will get the following output

Advertisement

Related Tags for PHP GD Replace Color:


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: November 10, 2009

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com