我正在尝试使用 PHP 和 GD 图像库向图像添加水印。我可以使用正确的不透明度设置在指定的位置应用水印。
问题是我的水印本身有透明背景。当我尝试将此水印应用到图像时,我得到黑色背景。
应用水印的图像是 jpeg。这可能是问题所在吗?如果是这样,我如何将 jpeg 转换为支持透明度的格式,应用水印,然后将其转换回来?
这是我目前拥有的关键代码。
// Determine image size and type
$size = getimagesize($this->image_path);
$size_x = $size[0];
$size_y = $size[1];
$image_type = $size[2]; // This is always a JPEG
// load source image
$image = $this->ImageCreateFromType($image_type, $this->image_path);
// Determine watermark size and type
$wsize = getimagesize($watermark_path);
$watermark_x = $wsize[0];
$watermark_y = $wsize[1];
$watermark_type = $wsize[2]; // This is typically a PNG
// load watermark
$watermark = $this->ImageCreateFromType($watermark_type, $watermark_path);
$dest_x = $this->setX($size_x, $watermark_x);
$dest_y = $this->setY($size_y, $watermark_y);
imagecopymerge($image, $watermark, $dest_x, $dest_y, 0, 0, $watermark_x, $watermark_y, $this->opacity);
虽然不是很相关,但这里是 ImageCreateFromType 函数的代码
function ImageCreateFromType($type,$filename) {
$im = null;
switch ($type) {
case 1:
$im = ImageCreateFromGif($filename);
break;
case 2:
$im = ImageCreateFromJpeg($filename);
break;
case 3:
$im = ImageCreateFromPNG($filename);
imagealphablending($im, true);
imagesavealpha($im, true);
break;
}
return $im;
}
阅读有关 imagecolortransparent() 函数的信息:http://php.net/manual/en/function.imagecolortransparent.php
您可能还想看看这个问题:使用 PHP 的 GDlib imagecopyresampled 时能否保留 PNG 图像透明度?
我知道这个答案有点晚了。但对于其他为此努力的人来说..
我也一直在尝试找到一种方法来解决同样的问题,我发现最有效的是以下解决方案:
$image_url = "The url of my image";
$watermark_image_url= "The url of my watermark image";
$watermark_image_size = 40; // percent of size relatively to the target image
$watermark_opacity = 50; // opacity 0-100
$im = imagecreatefromstring(file_get_contents($image_url));
$stamp = imagecreatefromstring(file_get_contents($watermark_image_url));
$margin_right = 10;
$margin_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, $margin_right, $margin_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);
}
它还适用于已经具有透明背景的图像,例如徽标图像。
我希望这有帮助