Imagecolortransparent() for multiple colors

687 Views Asked by At

I use this code to make all white pixels transparent:

$img = imagecreatefromjpeg('test.jpg');
$remove = imagecolorallocate($img, 255, 255, 255);
imagecolortransparent($img, $remove);
imagepng($img, 'bla.png');

But I also want some "almost white" pixels to be transparent like 254, 255, 255 etc. How could I add that?

2

There are 2 best solutions below

5
On BEST ANSWER

If your question is how to remove a contiguous area with similar color range; I must say that it's hard using PHP's GD library. You should take a look at ImageMagick which is a much more powerful image processing library and has PHP integration.

If you choose to use ImageMagick instead, you'll have access to a lot of third-party scripts that does amazing image processings. One of which is Fred Weinhaus' MagicWand. It does what you're looking for.

You seed it with an x and y coordinate, it can extract the color of that coordinate and make it transparent with a configurable color dissimilarity threshold (fuzz factor). Have a look how it can match a gradient of blue:

magicwand's magic

0
On

I had the same problem. With a black and white image. But white was not very white. So before to set transparency, I do a filter to increase the contrast. And I have an image with real black and real white. And when I use transparency on white color, it's works fine.

Filter's example :

imagefilter($src,IMG_FILTER_CONTRAST,-50);