使用 PHP GD 扩展的不透明效果

问题描述 投票:0回答:2

我想知道使用 PHP GD 扩展在其他图像上绘制图像时是否可以产生“不透明”效果?是否有任何内置函数可以得到我想要的结果,或者我必须使用

imagesetpixel
方式自己实现?

一个伪代码来说明我现在正在尝试做的事情:

// Background image
$image_bg = imagecreatetruecolor(100, 100);
imagesavealpha($image_bg, true);

// Making background image fully transparent
imagefill($image_bg, 0, 0, imagecolorallocatealpha($image_bg, 0, 0, 0, 127));

// Now the actual image I want to draw with opacity (true color PNG)
$image = imagecreatefrompng(...);

// Drawing with 50 "merge" value
imagecopymerge($image_bg, $image, ..., 50);

上述代码的问题在于

imagecopymerge
不会考虑背景图像的alpha值,并将图像与背景合并,就好像它是不透明的黑色一样(生成的图像不会是50%透明的)。

编辑:我最终使用

imagecolorat
imagesetpixel
方式实现了我自己的功能。

php gd
2个回答
0
投票

我一直在尝试在另一个图像上制作半透明水印图像。

经过一番努力后,我想出了以下解决方案。

$image_url = "url of my image";
$watermark_image_url= "url of my watermark image";
$watermark_image_size = 30; // percent of size relatively to the target image
$watermark_opacity = 60; // opacity 0-100

$im = imagecreatefromstring(file_get_contents($image_url));
$stamp = imagecreatefromstring(file_get_contents($watermark_image_url));

$marge_right = 10;
$marge_bottom = 10;

$stamp_w = imagesx($stamp);
$stamp_h = imagesy($stamp);

// Change the size of the watermark image
$percent_size = $watermark_image_size;
$percent_stamp_w = (int)($stamp_w * $percent_size / 100);
$percent_stamp_h = (int)($stamp_h * $percent_size / 100);

$stamp_imgResized = imagescale($stamp , $percent_stamp_w, $percent_stamp_h);

$opacity = (float)(watermark_opacity / 100);
$final_opacity = 127 - (int)(127*$opacity);

imagealphablending($stamp_imgResized, false);
imagesavealpha($stamp_imgResized, true);

imagefilter($stamp_imgResized, IMG_FILTER_COLORIZE, 0,0,0,$final_opacity); // the fourth parameter is alpha       

imagecopy($im, $stamp_imgResized, $marge_right, $marge_bottom, 0, 0, $percent_stamp_w, $percent_stamp_h);

// output to file
if (str_contains($thumbnail_image, '.png'))
{
    imagepng($im, $output);
} else if (str_contains($thumbnail_image, '.jpg'))
{
    imagejpeg($im, $output);
}

出于某种原因,为了使透明性发挥作用,需要满足以下条件

imagealphablending($stamp_imgResized, false);
imagesavealpha($stamp_imgResized, true);

-2
投票
© www.soinside.com 2019 - 2024. All rights reserved.