PHP&GD - 透明背景充满了附近的颜色

roc*_*est 6 php transparency gd image-processing

我知道PHP + GD透明度问题已经在这个和许多其他网站上被打死,但我已经遵循了所有的建议,我似乎无法解决我的问题.

一,解释:

我试图将一个图像叠加在另一个图像的顶部.他们都有透明的区域.作为一个我认识的演示应该看起来特别的方式,我试图在我创建的蓝色箭头形状上叠加一个复选标记.

以下是两张图片:

复选标记

蓝色箭头

现在到我的代码:

我正在使用我构建的库/ API来避免使用PHP + GD编辑图像时的痛苦.它还处于初期阶段,但相关的文件是:

基类
主加载器
(命名不佳)组合类

我正在使用以下脚本运行代码:

<?php
    require_once('Image.php');

    header("Content-Type: image/png");

    $img = new Image();
    $over = new Image();

    $img->source = "arrow.png";
    $over->source = "chk-done_24.png";

    $img->Combine->Overlay($over, 20, 20, 0, 0, $over->width, $over->height);
    $img->output();
    $img->clean();
    unset($img);
?>
Run Code Online (Sandbox Code Playgroud)

我希望输出是这样的:

组合图像

但相反,我得到了这个:

方底

如果填充区域是白色或黑色,我完全理解这个问题,但填充蓝色对我来说没有任何意义.

在上面链接的组合类I中,我还尝试了imagecopy,imagecopyresampled和vanilla imagecopymerge,两者都有类似的结果.

我完全失去了.

编辑:

要清楚,我的问题是:我的代码的哪一部分不正确?为什么用透明区域(而不是黑色或白色)填充透明区域?如何在保持透明合并图像的同时修复它?

更新:

请注意,当创建一个新的Image对象时,它会调用newImage包含以下代码的对象:

$this->handle = imagecreatetruecolor($this->width, $this->height);
imagealphablending($this->handle, false);
imagesavealpha($this->handle, true);
Run Code Online (Sandbox Code Playgroud)

我觉得这很容易错过.

Ano*_*mie 2

请注意,创建句柄newImageimagealphablending调用imagesavealpha它并不重要,因为loadImage会丢弃该句柄。

它用蓝色“填充”透明区域的原因是它根本没有用任何东西填充透明区域。它只是完全丢弃 Alpha 通道,而蓝色正是存储在 Alpha 为零的像素中的颜色。请注意,这在图形程序中可能很难看到,因为该程序本身可能会用黑色或白色替换完全透明的像素。

至于您的代码有什么问题,我不能肯定地说,因为当我尝试现有代码时,我没有得到与您报告的相同的结果。但是,如果我将您的更改loadImage为类似的内容,以便源图像被迫为真彩色,它对我有用:

            private function loadImage()
            {
                    $img = null;
                    switch( $this->type )
                    {
                            case 1:
                                            $img = imagecreatefromgif($this->source);
                                            break;
                            case 2:
                                            $img = imagecreatefromjpeg($this->source);
                                            break;
                            case 3:
                                            $img = imagecreatefrompng($this->source);
                                            break;
                            default:
                                            break;
                    }
                    if (!$img) return false;
                    $this->handle = imagecreatetruecolor($this->width, $this->height);
                    imagealphablending($this->handle, false);
                    imagesavealpha($this->handle, true);
                    imagecopyresampled($this->handle, $img, 0, 0, 0, 0, $this->width, $this->height, $this->width, $this->height);
                    return true;
            }
Run Code Online (Sandbox Code Playgroud)

(就我个人而言,我更喜欢 ImageMagick 而不是 GD)。