在PHP中使用透明度合并两个图像

时间:2011-06-23 17:55:53

标签: php png gd alphablending

我正在尝试通过php使用背景透明度制作几个.png的合成图像,并将生成的图像存储在我的数据库中。我的问题是,当合并图像时,我的图像的透明部分被丢弃。

这是我创建合成图像的代码:

    $base = imagecreatefrompng('application/assets/images/vel1_bg.png');
    imagealphablending($base, true);
    list($baseWidth, $baseHeight, $type, $attr) = getimagesize('application/assets/images/vel1_bg.png');

    $user_board_items = $this->config->item('user_board_items');

    foreach($array as $key => $value){
        $item = imagecreatefrompng('application/assets/images/items/' . $user_board_items[$value[0]] . '.png');         
        imagealphablending($item, true);
        list($width, $height, $type, $attr) = getimagesize('application/assets/images/items/'. $user_board_items[$value[0]] . '.png');

        imagecopymerge($base,
                    $item,
                    floor(($value[1] / 100) * $baseWidth),
                    floor(($value[2] / 100) * $baseHeight),
                    0,
                    0,
                    $width,
                    $height,
                    100);
        imagedestroy($item);
    }

    //We have to capture the output buffer
    ob_start();
    imagepng($base);
    $baseimg = ob_get_clean();

这会生成如下图像: enter image description here

我正在寻找更像这样的东西: enter image description here (注意如何表示透明部分)

2 个答案:

答案 0 :(得分:4)

不要使用imagecopymerge()来合并透明图像。

最好在脚本中使用imagecopyresampled()。

答案 1 :(得分:0)

如前所述,imagecopyresampled在经过数小时尝试不同的解决方案之后也为我工作。要传递的参数保持不变,除了您必须删除最后一个,但添加源宽度和高度。你的电话可能是:

  imagecopyresampled($base,
                $item,
                floor(($value[1] / 100) * $baseWidth),
                floor(($value[2] / 100) * $baseHeight),
                0,
                0,
                $width,
                $height,
                $width,
                $height);
相关问题