imagecolortransparent()在PHP中将所有黑色像素变为透明

时间:2012-08-16 13:37:05

标签: php image image-processing php-gd

是的,所以我开始在PHP中构建一个函数,可以将两个图像合并在一起,同时保留PNG文件的透明背景 - 我成功完成了 - 使用下面的代码,

function imageCreateTransparent($x, $y) {

    $imageOut = imagecreatetruecolor($x, $y);
    $colourBlack = imagecolorallocate($imageOut, 0, 0, 0);
    imagecolortransparent($imageOut, $colourBlack);
    return $imageOut;
}



function mergePreregWthQR($preRegDir, $qrDir){

$top_file = $preRegDir;
$bottom_file = $qrDir;


$top    = imagecreatefrompng($top_file);
$bottom = imagecreatefrompng($bottom_file);

// get current width/height
list($top_width, $top_height) = getimagesize($top_file);
list($bottom_width, $bottom_height) = getimagesize($bottom_file);

// compute new width/height
$new_width = ($top_width > $bottom_width) ? $top_width : $bottom_width;
$new_height = $top_height + $bottom_height;

// create new image and merge
$new = imageCreateTransparent($new_width,$new_height);
imagecopy($new, $bottom, 0, $top_height+1, 0, 0, $bottom_width, $bottom_height);
imagecopy($new, $top, 0, 0, 0, 0, $top_width, $top_height);

$filename = "merged_file.png";

// save to file
imagepng($new, $filename);

}

mergePreregWthQR("file.png", "qr.png");

这设法合并两个图像并保持透明背景,唯一的问题是合并图像中的任何黑色像素变为透明,此合并的结果显示在此处> merged image

顶部图像是水母图像,底部是QR码,只有当图像放置在白色以外的任何背景上时才能看到。所以我非常肯定会发生这种情况, imagecolortransparent($ imageOut,$ colourBlack); 将新创建的merged_file.png中的每个黑色像素变为透明。我通过稍微改变imageCreateTransparent($ x,$ y)来测试理论,如下所示:

function imageCreateTransparent($x, $y) {

$imageOut = imagecreatetruecolor($x, $y);
$colourBlack = imagecolorallocate($imageOut, 55, 55, 55);
imagefill ( $imageOut, 0, 0, $colourBlack );

imagecolortransparent($imageOut, $colourBlack);

return $imageOut;

}

所以在这个函数中,我用颜色(55,55,55)填充整个图像,然后在我的imagecolortransparent()函数中将此颜色设置为透明。这样做的伎俩,我的QR码显示应该是。唯一的问题是,我认为这是一个快速而肮脏的黑客,如果有人在上传的图像中有颜色(55,55,55),它将变得透明?所以我很想知道另一种解决方案是什么?感谢。

1 个答案:

答案 0 :(得分:0)

您是否尝试仅在顶部图像上将黑色像素设置为透明,然后进行复制?

The PHP manual states: "透明度仅使用imagecopymerge()和真彩色图像复制,而不是使用imagecopy()或pallete图像复制。"

因此,这可能是在复制其他两个之前在最终图像上应用透明度的替代解决方案。

另一件可能值得关注的事情是:imagealphablending。在php网站的评论中已经提到,设置错误可能会影响已应用alpha的图像的分层。

相关问题