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

标签 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();

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

最佳答案

看起来您想按原样发送 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/

相关文章:

php - Netbeans IDE (6.8/PHP) - 自定义窗口排列?

php - 如何将 CSS 减少到几个属性

java - 创建具有透明背景的图标

c# - Windows 窗体 - 以透明为背景的 PNG

css - IE 的图像和透明过滤器问题

php - 如何检查行是否已更新?

javascript - Dropzone.js - 上传后的成功消息

c++ - 通过C++中的坐标获取png

javascript - 带有生成的 png 的跨浏览器 CSS3

javascript - 带有外部蒙版透明fabricjs的蒙版对象