Invert color and preserve transparency with PHP

I am trying to create a function that receives a PNG image and returns it with inverted colors. However, I am having problems with the transparent / alpha channel: basically, transparent pixels are returned as black or white and hence the transparency is not preserved.

This is an example of the original image (which of course will change), PNG with a transparent background:

enter image description here

I would like to invert these colors while keeping the transparency / alpha channel like CTRL + i in Photoshop. I am using GD function imagefilter

with parameterIMG_FILTER_NEGATE

With code:

$im = imagecreatefrompng($image_file);

imagefilter($im, IMG_FILTER_NEGATE);

header('image/png');

imagepng($im,NULL,0);

      

But this gives:

enter image description here

As you can see, the transparent pixels have turned black.

Then I tried to add an alpha channel to the imagecreatefrompng function (like this ):

$im = imagecreatefrompng($image_file);

imagealphablending($im, false);

imagesavealpha($im, true);

imagefilter($im, IMG_FILTER_NEGATE);

header('image/png');

imagepng($im,NULL,0);

      

But now I go white instead of black:

enter image description here

Now the problem comes after the function is applied imagefilter

. For example, if I run this code:

$im = imagecreatefrompng($image_file);

imagealphablending($im, false);

imagesavealpha($im, true);

//imagefilter($im, IMG_FILTER_NEGATE);

header('image/png');

imagepng($im,NULL,0);

      

The output image retains its transparent background while remaining identical to the original image.

How can I invert the colors of transparent PNGs without losing the transparent background?

NOTE: this is not the same question as imagecreatefrompng () makes the background black instead of transparent? - the inversion step is the tricky part here

+3
php gd


source to share


No one has answered this question yet

See similar questions:

33
imagecreatefrompng () Makes the background black instead of transparent?

or similar:

4270
Link. What does this symbol mean in PHP?
2776
How can I prevent SQL injection in PHP?
2414
Why shouldn't I use the mysql_ * functions in PHP?
2335
Removing an element from an array in PHP
15
GD! Convert png image to jpeg and create alpha by default white instead of black
6
Combine two transparent PNG images
3
PHP / GD ImageSaveAlpha and ImageAlphaBlending
3
PHP + GD: imagetruecolortopalette does not preserve transparency
0
PHP Eventviva extends png transparency
0
PHP 5.5 imagecropauto () lost transparency



All Articles
Loading...
X
Show
Funny
Dev
Pics