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


source to share





All Articles