GDlib PHP - png到gif将背景透明变为黑色

GDlib PHP  -  png到gif将背景透明变为黑色

问题描述:

When trying to convert PNG to GIF, return transparent to black:

$file = "example.png"

$whf = getimagesize($file); 
$wf = $whf[0];
$hf = $whf[1];

$h = "100";
$w = "100";

$img = imagecreatetruecolor($w, $h);
$imgi = imagecreatefrompng($file);

// Here means to be some magic code...

imagecopyresampled($img, $imgi, 0, 0, 0, 0, $w, $h, $wf, $hf);
imagegif($img, "example.gif");

imagedestroy($img);

Codes I've tryed but nothing:

1º:

imagesavealpha($img, true);
imagecolortransparent($img, 127<<24);

2º:

imagealphablending($img, false);
imagesavealpha($img, true);

This works! But with one detail. You need absolute transparent background without "png gradients transparencies". Imagick uses half gradient transparencies to absolute transparent and other half to absolute plain. Thanks isalgueiro!

$black = imagecolorallocate($img, 0, 0, 0);
imagecolortransparent($img, $black);    

I think you need to call imagecolorallocate to get the color reference and pass that to imagecolortransparent:

$black = imagecolorallocate($im, 0, 0, 0);
imagecolortransparent($img, $black);