【问题标题】:Transparency with background image using GD使用 GD 的背景图像透明度
【发布时间】:2009-07-20 07:11:39
【问题描述】:

使用 GD2 填充纯色透明 png,这是我的代码和结果。基本上,一旦透明度开始,填充颜色就会突然停止,而不是与透明度混合。

private function GenerateImage()
{
    $original = imagecreatefrompng($this->ImagePath());

    $x = imagesx($original);
    $y = imagesy($original);

    $image = imagecreate($x,$y);

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

    imagecopyresampled($image,$original,0,0,0,0,$x,$y,$x,$y);

    $colour = imagecolorallocate($image,$this->RGB[0],$this->RGB[1],$this->RGB[2]);
    imagefill($image,0,0,$colour);

    return imagepng($image,$this->GeneratedPath());

    imagedestroy($original);
    imagedestroy($image);
}

原图:

alt text http://far.id.au/jkf/so/blank.png

生成的图像:

alt text http://far.id.au/jkf/so/filled.png

【问题讨论】:

    标签: php transparency gd


    【解决方案1】:

    我认为你的做法是错误的,如果你想让透明图像出现在颜色之上,那么你需要先填充然后复制图像。

    此外,如果您使用透明度,则需要调用 imagecreatetruecolor();而不是 imagecreate();

    private function GenerateImage()
    {
            $original = imagecreatefrompng($this->ImagePath());
    
            $x = imagesx($original);
            $y = imagesy($original);
    
            $image = imagecreatetruecolor($x,$y);
    
            imagealphablending($image,true);
            imagesavealpha($image,true);
    
            $colour = imagecolorallocate($image,$this->RGB[0],$this->RGB[1],$this->RGB[2]);
            imagefill($image,0,0,$colour);
    
            imagecopyresampled($image,$original,0,0,0,0,$x,$y,$x,$y);
    
            return imagepng($image,$this->GeneratedPath());
    
            imagedestroy($original);
            imagedestroy($image);
    }
    

    如果您尝试在图像顶部绘制红色,则使用 imagefilledrectangle() 而不是 imagefill()。由于某种原因,图像填充似乎不适用于透明胶片。

    // Replace
    imagefill($image,0,0,$colour);
    // With
    imagefilledrectangle( $image, 0,0, $x,$y,$colour);
    

    【讨论】:

    • 谢谢!我喜欢将 GD 与 PHP 结合使用,但仍有很多需要学习的地方。
    猜你喜欢
    • 2013-02-21
    • 2016-09-06
    • 1970-01-01
    • 2011-11-10
    • 1970-01-01
    • 2016-12-08
    • 2011-10-16
    • 2012-04-19
    • 1970-01-01
    相关资源
    最近更新 更多