PHP GD Image Library change image color - gif works but jpegs wont

Thanks for taking the time to read my problem:

I'm using the following code to get an image and then change the color 201,2,255 (r,g,b) - which is a shade of purple then output the image.

$imgname = "input.gif";
$im = imagecreatefromgif ($imgname);

$index = imagecolorclosest ( $im,  201,2,255 ); // get White COlor
imagecolorset($im,$index,60,140,48); // SET NEW COLOR

$imgname = "output.gif";
imagegif($im, $imgname ); // save image as gif
imagedestroy($im);

This works perfectly which can be seen here : http://www.office-desks.co.uk/cache_images/test.php (top 2 images)

The problem is when I try todo exactly the same but using a jpeg instead it doesn't work.. (bottom 2 images)

$imgname = "input.jpg";
$im = imagecreatefromjpeg ($imgname);

$index = imagecolorclosest ( $im,  201,2,255 ); // get pink/purple COlor
imagecolorset($im,$index,60,140,48); // SET NEW DECENT COLOR

$imgname = "output.jpg";
imagejpeg($im, $imgname ); // save image as gif
imagedestroy($im);

If anyone could help me shed some light on the problem, would be much appreciated. Thanks in advance all.

Upvotes: 0

Views: 554

Answers (1)

Sebastiaan
Sebastiaan

Reputation: 11

A bit late, but I think that has to do with the 'artifacts' (compression errors) generated by JPG. Zoom in on a JPG and you see 'grains' of pixels that won't match the neighbors. This means big planes of a single color will become many colors and not 1 single value.

Stick with lossless image formats like gif or png.

Upvotes: 1

Related Questions