Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace a color with another in an image with PHP

Tags:

php

gd

Can someone help me with a simple script to replace a specific color with another color in an image using PHP? Here is a example (color changed from green to yellow).

beforeafter

like image 659
Florin Frătică Avatar asked Aug 29 '12 13:08

Florin Frătică


People also ask

How do I recolor certain parts of an image?

Go to the Image menu, then to Adjustments , and choose Replace Color . When the dialog box opens, the first step is to sample the color in the image you want to replace by clicking on it. Now go to the Hue , Saturation , and Lightness controls to set the color you want to use as a replacement.

What is swap color?

Color Swapping simply refers to the idea of substituting a specific color/colors in an image with some targeted color for the purpose of exploration, design, image creation, etc.


1 Answers

If you meant using GD library in PHP, you should give a check on imagefilter()

Steps are:

  • Start with a .PNG image, use white for inner, alpha for outer.
  • Use imagefilter($img, IMG_FILTER_COLORIZE, 0, 255, 0)) Where 0,255,0 is your RGB color (bright green in this example)
  • Save the alpha and print out result.

Edit, Working code and clarification.

I meant, using alpha for OUTER of the black lines, and white INSIDE. Here's the sample image: WhiteInAlphaOut

And here's a working code for colorizing white parts:

header('Content-Type: image/png');

/* RGB of your inside color */
$rgb = array(0,0,255);
/* Your file */
$file="../test.png";

/* Negative values, don't edit */
$rgb = array(255-$rgb[0],255-$rgb[1],255-$rgb[2]);

$im = imagecreatefrompng($file);

imagefilter($im, IMG_FILTER_NEGATE); 
imagefilter($im, IMG_FILTER_COLORIZE, $rgb[0], $rgb[1], $rgb[2]); 
imagefilter($im, IMG_FILTER_NEGATE); 

imagealphablending( $im, false );
imagesavealpha( $im, true );
imagepng($im);
imagedestroy($im);

Note: We must negate values since colorize only works for non-white parts. We could have a workaround to this by having white-bordered image with black inside.

Note: This code only works for black-border and white-inner images.

like image 62
Touki Avatar answered Sep 26 '22 01:09

Touki