我在渲染 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();
结果在所有现代浏览器中都是相同的。怎么可能,有什么想法吗? 代码是类的一部分,适用于所有类型的图像,并且所有功能都可以正常工作。
最佳答案
看起来您想按原样发送 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();
关于php - 为什么修复 GD 的 png 透明度问题的解决方案不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28557324/