使用 PHP 创建透明的 png 文件

2022-08-30 21:30:45

目前,我想创建一个质量最低的透明png。

代码:

<?php
function createImg ($src, $dst, $width, $height, $quality) {
    $newImage = imagecreatetruecolor($width,$height);
    $source = imagecreatefrompng($src); //imagecreatefrompng() returns an image identifier representing the image obtained from the given filename.
    imagecopyresampled($newImage,$source,0,0,0,0,$width,$height,$width,$height);
    imagepng($newImage,$dst,$quality);      //imagepng() creates a PNG file from the given image. 
    return $dst;
}

createImg ('test.png','test.png','1920','1080','1');
?>

但是,存在一些问题:

  1. 在创建任何新文件之前,我是否需要指定 png 文件?或者我可以在没有任何现有png文件的情况下创建吗?

    警告:imagecreatefrompng(test.png):无法打开流:中没有这样的文件或目录

    C:\DSPadmin\DEV\ajax_optipng1.5\create.php在第 4 行

  2. 虽然有错误信息,它仍然会生成一个png文件,但是,我发现的是该文件是黑色图像,我是否需要指定任何参数才能使其透明?

谢谢。


答案 1

To 1)尝试打开文件,然后可以使用GD函数进行编辑。imagecreatefrompng('test.png')test.png

到 2) 启用 Alpha 通道的保存。下面的代码通过启用 Alpha 保存并用透明度填充它来创建一个 200x200px 大小的透明图像。imagesavealpha($img, true);

<?php
$img = imagecreatetruecolor(200, 200);
imagesavealpha($img, true);
$color = imagecolorallocatealpha($img, 0, 0, 0, 127);
imagefill($img, 0, 0, $color);
imagepng($img, 'test.png');

答案 2

看看:

一个示例函数复制透明的 PNG 文件:

    <?php
    function copyTransparent($src, $output)
    {
        $dimensions = getimagesize($src);
        $x = $dimensions[0];
        $y = $dimensions[1];
        $im = imagecreatetruecolor($x,$y); 
        $src_ = imagecreatefrompng($src); 
        // Prepare alpha channel for transparent background
        $alpha_channel = imagecolorallocatealpha($im, 0, 0, 0, 127); 
        imagecolortransparent($im, $alpha_channel); 
        // Fill image
        imagefill($im, 0, 0, $alpha_channel); 
        // Copy from other
        imagecopy($im,$src_, 0, 0, 0, 0, $x, $y); 
        // Save transparency
        imagesavealpha($im,true); 
        // Save PNG
        imagepng($im,$output,9); 
        imagedestroy($im); 
    }
    $png = 'test.png';

    copyTransparent($png,"png.png");
    ?>

推荐