【问题标题】:PHP GD : Can i just fill transparent part?PHP GD:我可以只填充透明部分吗?
【发布时间】:2012-07-14 10:24:12
【问题描述】:

有一个图像具有透明区域。 (PNG图片) 现在,在进行图像复制时,我们可以只填充那个透明区域吗?

Imagemagick 可以轻松做到这一点。这在 php gd 中可能吗?

【问题讨论】:

    标签: php gd


    【解决方案1】:

    通过imagecopymerge() 的分层方法是一种方法。这个概念是将您的源图像合并到具有预设背景图像的新图像上,该背景图像将在合并后通过源图像的透明度显示。

    //create main image - transparent, with opaque red square in middle
    $img = imagecreate(60, 60);
    $white = imagecolorallocate($img, 255, 255, 255);
    imagecolortransparent($img, $white); //make background transparent
    $red = imagecolorallocate($img, 255, 0, 0);
    imagefilledrectangle($img, imagesx($img) / 4, imagesy($img) / 4, imagesx($img) - (imagesx($img) / 4), imagesy($img) - (imagesy($img) / 4), $red);
    
    //create new image, with pre-filled background, then merge first image across
    $img2 = imagecreate(60, 60);
    $blue = imagecolorallocate($img2, 0, 0, 255);
    imagecopymerge($img2, $img, 0, 0, 0, 0, imagesx($img), imagesy($img), 100);
    
    //output
    imagepng($img2);
    

    所以第一个图像创建了一个透明图像(白色),中间有一个红色方块。第二张图片只是一个蓝色填充。将两者合并,蓝色通过第一张图片的透明部分显示出来,所以我们的红色方块现在位于蓝色填充上。实际上,我们已经填充了透明部分。

    这是按顺序排列的三个状态。

      【讨论】:

        【解决方案2】:

        在透明的地方没有什么可以“填充”的。 png(或 gif)中的透明度不是没有颜色,而是专门标记为透明的单一颜色。因此,您要删除该标记。

        看看php gds函数'imagecolortransparent':

        【讨论】:

          【解决方案3】:

          不,你不能。 相反,您可以尝试从彩色矩形创建副本。这段代码对我有用:

          $input = imagecreatefrompng($file_input);
          list($width, $height) = getimagesize($file_input);
          $output = imagecreatetruecolor($width, $height);
          $white = imagecolorallocate($output,  255, 255, 255);
          imagefilledrectangle($output, 0, 0, $width, $height, $white);
          imagecopy($output, $input, 0, 0, 0, 0, $width, $height);
          imagepng($output, $file_output);
          

          【讨论】:

            猜你喜欢
            • 2015-10-13
            • 2016-08-25
            • 1970-01-01
            • 2013-02-21
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2012-08-24
            相关资源
            最近更新 更多