Easy Guide to Replace Image Color: Tips and Tricks

This easy guide provides you with effective tips and tricks for replacing image colors. Learn how to modify image hues and tones, change backgrounds, adjust color.

Sure, here's an updated PHP code snippet that demonstrates how to replace colors in an image of any type (including PNG, JPEG, and GIF) using the GD library in PHP

 
    $source_file="test.png";
        $from_color['r']="253";
        $from_color['g']="237";
        $from_color['b']="203";
        $to_color['r']="0";
        $to_color['g']="0";
        $to_color['b']="0";

        $imgsize = getimagesize($source_file);
        $mime = $imgsize['mime'];


        switch ($mime) {
            case 'image/gif':
                $image_create = "imagecreatefromgif";
                $image = "imagegif";
                break;

            case 'image/png':
                $image_create = "imagecreatefrompng";
                $image = "imagepng";
                $quality = 7;
                break;

            case 'image/jpeg':
                $image_create = "imagecreatefromjpeg";
                $image = "imagejpeg";
                $quality = 80;
                break;
            default:
                return false;
                break;
        }

       $im = $image_create($source_file);
        imageAlphaBlending($im, true);
        imageSaveAlpha($im, true);
        imagetruecolortopalette($im,false, 255);
        $index = imagecolorclosest ( $im,$from_color['r'],$from_color['g'],$from_color['b']); // get White COlor
        imagecolorset($im,$index,$to_color['r'],$to_color['g'],$to_color['b']); // SET NEW COLOR
        header('Content-Type: image/png');
        $image($im);