我目前正在编写一个脚本,为图像添加水印。所述水印的不透明度不同。例如,基本水印图像是具有完全可见文本和透明背景的PNG。当添加时,我想淡出这个基础PNG,以满足我的需要,并使一个不透明的水印。
为此,我使用imagefilter()淡出PNG:
$opacity = 0.25;
$watermarkRes = imagecreatefrompng($filename);
imagealphablending($watermarkRes, false);
imagesavealpha($watermarkRes, true);
$transparency = 1 - $opacity;
imagefilter(
$watermarkRes,
IMG_FILTER_COLORIZE,
0,
0,
0,
127*$transparency
);
imagepng($watermarkRes, $filename);所有不透明的区域都会很好地褪色,但现有的透明区域会变黑。
这是上述代码的结果:
https://preview.ibb.co/j8zePF/TEST.png
用作水印,如下所示:
https://preview.ibb.co/mLvKPF/15027295625991d55a1ef081_42502547.jpg
而期望的结果应该是:
https://preview.ibb.co/f81R4F/TEST_15027295625991d55a1ef081_42502547.jpg
如何在保持透明区域不变的同时增加文本的不透明度?
发布于 2017-09-06 05:59:46
不要紧。问题不在于函数本身,而在于我事先根据使用情况调整了水印的高度。
我删除了这段代码来调整水印的大小:
$new_image = imagecreatetruecolor($width, $height);
imagecopyresampled($new_image, $watermarkRes, 0, 0, 0, 0, $width, $height, imagesx($watermarkRes), imagesy($watermarkRes));
$watermarkRes = $new_image;并使用此问题的答案中提供的Dycey的调整大小代码:
How do I resize pngs with transparency in PHP?
在我的例子中,我创建了这个函数来调整图像的大小:
/**
* @param int $width
* @param int $height
*/
public function resize($width, $height)
{
$new_image = imagecreatetruecolor($width, $height);
if($this->image_type === IMAGETYPE_PNG || $this->image_type === IMAGETYPE_GIF) {
imagealphablending($new_image, false);
imagesavealpha($new_image,true);
$transparent = imagecolorallocatealpha(
$new_image, 255, 255, 255, 127
);
imagefilledrectangle(
$new_image, 0, 0, $width, $height, $transparent
);
}
imagecopyresampled(
$new_image,
$this->image,
0, 0, 0, 0,
$width, $height,
imagesx($this->image), imagesy($this->image)
);
$this->image = $new_image;
}https://stackoverflow.com/questions/46061803
复制相似问题