Can I swap colors in image using GD library in PHP?

This will replace the white color with Gray

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

$index = imagecolorclosest ( $im,  255,255,255 ); // get White COlor
imagecolorset($im,$index,92,92,92); // SET NEW COLOR

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

enter image description here


I had trouble making this solution work. The image cannot be a true color image. Convert it first with imagetruecolortopalette();

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

imagetruecolortopalette($im,false, 255);

$index = imagecolorclosest ( $im,  255,255,255 ); // get White COlor
imagecolorset($im,$index,92,92,92); // SET NEW COLOR

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