为什么修复GD的png透明度问题的解决方案不起作用?

时间:2015-02-17 08:07:21

标签: php png transparency php-gd

我在渲染png上有这个代码(简化):

$this->image = imagecreatefrompng($this->file);
header("Content-Type: {$this->imageInfo['mime']}");
imagepng($this->image);

在我获得黑色背景后,我找到了一些解决方案,但这些解决方案并没有起作用。更容易:

$this->image = imagecreatefrompng($this->file);
imagealphablending($targetImage, false);
imagesavealpha($targetImage, true);
header("Content-Type: {$this->imageInfo['mime']}");
imagepng($this->image);exit();

人们声称它有效,但我仍然有黑色背景,所以我尝试了另一个:

$this->image = imagecreatefrompng($this->file);
$targetImage = imagecreatetruecolor($this->imageInfo[0], $this->imageInfo[1]);
imagealphablending($targetImage, false);
$color = imagecolorallocatealpha($targetImage, 0, 0, 0, 127);
imagefill($targetImage, 0, 0, $color);
imagecolortransparent($targetImage, $color);
imagesavealpha($targetImage, true);
imagecopyresampled($targetImage, $this->image, 0, 0, 0, 0, $this->imageInfo[0], $this->imageInfo[1], $this->imageInfo[0], $this->imageInfo[1]);
header("Content-Type: {$this->imageInfo['mime']}");
imagepng($this->image);exit();

结果在所有现代浏览器中都是相同的。怎么可能,任何想法? 代码是类的一部分,它适用于所有类型的图像,并且所有功能都能正常工作。

1 个答案:

答案 0 :(得分:1)

好像你想按原样发送png文件,为什么要先用GD转换呢?我只想使用readfile()并输出文件:

header("Content-Type: {$this->imageInfo['mime']}");
readfile($this->file);
exit();

对于您的其他测试:

您希望最后输出$targetImage而不是$this->image,否则不会发生什么奇特的事情。此外,我认为您需要在imagecopyresampled之前启用Alpha混合,而不是禁用它,以避免黑色边框。

$this->image = imagecreatefrompng($this->file);
$targetImage = imagecreatetruecolor($this->imageInfo[0], $this->imageInfo[1]);

$color = imagecolorallocatealpha($targetImage, 0, 0, 0, 127);
imagefill($targetImage, 0, 0, $color);
imagecolortransparent($targetImage, $color);
imagealphablending($targetImage, true);
imagecopyresampled($targetImage, $this->image, 0, 0, 0, 0, $this->imageInfo[0], $this->imageInfo[1], $this->imageInfo[0], $this->imageInfo[1]);
header("Content-Type: {$this->imageInfo['mime']}");
imagepng($targetImage);
exit();