Is it possible to create an PNG with full alpha channel by using: imagecolortransparent()

1.4k Views Asked by At

I'm looking for a way to create a transparent area in an image by using its aplha channel.

I just found that way:

Define a color and set it to transparent.

imagealphablending($img, false);   // has to be false for imagecolortransparent
imagesavealpha($img, false);       // false = single color transparency

$mask_color = imagecolorallocatealpha($img, 0, 255, 0, 127);
imagecolortransparent( $img, $mask_color );

But the result is a single color transparency. If i try to merge it with an image with alpha channel, the mask color gets visible again.

This happens at the moment i enable imagesavealpha() again, needed for that merge prozess.

By the way: I create the $img by merging a source image with an mask image.

$new_img = imagecreatetruecolor( 150, 100 );
$new_white = imagecolorallocatealpha( $new_img, 255, 255, 255, 0 );
imagefill( $new_img, 0, 0, $new_white );

imagealphablending($new_img, false);   // has to be false for full alpha
imagesavealpha($new_img, true);       // true = full alpha channel

imagecopyresampled( $new_img, $img       ,0, 0, 0, 0, 150, 100, 150, 100);
imagecopyresampled( $new_img, $alpha_img ,0, 0, 0, 0, 150, 100, 150, 100);

// save preview
imagepng( $new_img, $image_path . $preview_dir_name . $new_file_name );

The transparent areas from $img are now visible again.

So, is there a way to make an specific colored area transparent by using the full alpha channel?

1

There are 1 best solutions below

0
On

I found a way:

// get source image
$img = imagecreatefromjpeg( $image_path . $image_file );

// save transparency in alpha channel
imagealphablending($img, false);
imagesavealpha($img, true);

// define index for transparent color
$transparent = imagecolorallocatealpha( $preview_temp, 255, 255, 255, 127 );

// replace pixel information
imagesetpixel( $img, $x, $y, $transparent );

using imagesetpixel() I can replace a pixel and get transparent areas in a given picture by using its alpha channel.

It works for me and perhaps I will post the complete code later.

But do you know an other solution?