【问题标题】:Why solution to fix png transparency issue of GD does not work?为什么解决 GD 的 png 透明度问题的解决方案不起作用?
【发布时间】:2015-04-17 21:39:20
【问题描述】:

我在渲染 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();

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

【问题讨论】:

    标签: php png transparency php-gd


    【解决方案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();
    

    【讨论】:

    • 哇,第一点你是对的,但我不需要 imagecopyresampled(这只是测试)。我只需要通过 PHP 显示 png(代码的第一部分)。如果没有 imagecopyresampled,你知道怎么做吗?谢谢
    • 然后不要将其转换为 png 并返回,只需使用 readfile 按原样发送文件,请参见示例 #1 here
    • 我试过了(readfile),但我仍然得到黑色图片而不是透明图片。这很奇怪,不是吗?
    • 那么磁盘上的png可能不透明?
    • 是的,有一些逻辑错误,但您的建议(readfile)确实帮助我找到了问题的核心。谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-25
    • 2023-03-24
    相关资源
    最近更新 更多