【问题标题】:imagecolortransparent() turns all black pixels transparent in PHPimagecolortransparent() 在 PHP 中将所有黑色像素变为透明
【发布时间】:2012-08-16 13:37:05
【问题描述】:

是的,所以我开始在 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

上图为水母图片,下图为二维码,只有将图片放在非白色背景上才能看到。所以我很确定正在发生的是 imagecolortransparent($imageOut, $colourBlack); 将新创建的 merge_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),它会变成透明的吗?所以我很想知道另一种解决方案是什么?谢谢。

【问题讨论】:

  • 你解决过这个问题吗?我也有同样的问题...

标签: php image image-processing php-gd


【解决方案1】:

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

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

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

另一件可能值得一看的是:imagealphablending。在 php 网站上的 cmets 中已经提到,如果设置不正确会影响应用了 alpha 的图像的分层。

【讨论】:

    猜你喜欢
    • 2012-07-30
    • 2013-08-21
    • 1970-01-01
    • 1970-01-01
    • 2011-03-26
    • 2016-06-14
    • 2011-03-04
    • 1970-01-01
    • 2014-05-27
    相关资源
    最近更新 更多