在PHP中使用imagecopymerge在图像上添加一些不透明度



这里是我的问题:

我想通过将图像复制到另一个透明图像上来更改图像的不透明度。

我的代码:

$opacity = 50;
$transparentImage = imagecreatetruecolor($width, $height);
imagesavealpha($transparentImage, true);
$transColour = imagecolorallocatealpha($transparentImage , 0, 0, 0, 127);
imagefill($transparentImage , 0, 0, $transColour);
imagecopymerge($transparentImage, $image, 0, 0, 0, 0, $width, $height, $opacity);
$image = $transparentImage;
header('Content-type: image/png');
imagepng($image);

这样,当我使用imagecopymerge时,$transparentImage会失去透明度。。。所以$image被合并到一个黑色图像上。。。而不是在透明图像上!

但是,当我在调用imagecopymerge之前显示$transparentImage时,该图像在导航器中是透明的!

有没有一个解决方案可以在不添加彩色背景的情况下更改图像的不透明度?

imagecopymerge似乎不支持图像上的alpha(透明度)通道。幸运的是,您可以使用imagecopy的变通方法来正确地执行此操作。以下是一个函数,它取自php.net上的注释:

function imagecopymerge_alpha($dst_im, $src_im, $dst_x, $dst_y, $src_x, $src_y, $src_w, $src_h, $pct){
    // creating a cut resource
    $cut = imagecreatetruecolor($src_w, $src_h);
    // copying relevant section from background to the cut resource
    imagecopy($cut, $dst_im, 0, 0, $dst_x, $dst_y, $src_w, $src_h);
    // copying relevant section from watermark to the cut resource
    imagecopy($cut, $src_im, 0, 0, $src_x, $src_y, $src_w, $src_h);
    // insert cut resource to destination image
    imagecopymerge($dst_im, $cut, $dst_x, $dst_y, 0, 0, $src_w, $src_h, $pct);
} 

最新更新