【问题标题】:PHP: Adding opacity with imagefilter() blackens already transparent areasPHP:使用 imagefilter() 添加不透明度会使已经透明的区域变黑
【发布时间】:2018-02-14 03:40:03
【问题描述】:

我目前正在编写一个脚本来为图像添加水印。所述水印的不透明度不同。 例如,基础水印图像是具有完全可见文本和透明背景的 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

如何在保持透明区域不变的同时为文本添加不透明度?

【问题讨论】:

    标签: php image png transparency imagefilter


    【解决方案1】:

    没关系。问题不在于函数本身,而在于我事先根据使用情况调整了水印的高度。

    我删除了这段代码来调整水印的大小:

    $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;
    }
    

    【讨论】:

      猜你喜欢
      • 2011-08-20
      • 1970-01-01
      • 2013-04-28
      • 1970-01-01
      • 2012-12-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-01
      相关资源
      最近更新 更多