phpimagegdtransparent

I'm trying to make a image transparent using GD library from PHP but running following code, only a portion will be transparent


I'm trying to make a image transparent using GD library from PHP but running following code, only a portion will be transparent.

$image = imagecreatefrompng("$second");  
imagealphablending($image, false);
$col_transparent = imagecolorallocatealpha($image, 0, 0, 0, 127);
imagefill($image, 0, 0, $col_transparent);  // set the transparent colour as the background.
imagecolortransparent ($image, $col_transparent); // actually make it transparent
imagesavealpha($image, TRUE);
header( 'Content-Type: image/png' );
imagepng($image);

Here you have original image: https://postimg.org/image/y68nw57z1/
Here it's the resulting image: https://postimg.org/image/o4n3t6ic7/

As you can see, exists parts from the resulting image that remain white.
How i can resolve this?


Solution

  • You are flood-fill replacing the white pixels of your image but that won't work on pixels that are completely enclosed by non-white pixels (as in any paint program). Instead you can modify the definition of the colour white to make it transparent:

    $image = imagecreatefrompng($second);
    imagetruecolortopalette($image, false, 255);
    $index = imagecolorclosest($image, 255, 255, 255); // find index of white.
    imagecolorset($image, $index, 0, 0, 0, 127); // replace white with transparent black.
    header('Content-Type: image/png');
    imagepng($image);