使用PHP创建透明的PNG文件

24

目前我想创建一张最低质量的透明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文件,但我发现该文件是黑色图像,请问是否需要指定任何参数使其透明?

谢谢。

3个回答

53

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

对于2) 为了启用alpha通道的保存,可以使用imagesavealpha($img, true);。 以下代码通过启用alpha保存并用透明度填充来创建一个200x200像素大小的透明图像。

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

谢谢你的帮助!你介意教我如何最小化PNG文件的大小吗?在imagepng函数中设置“9”质量级别是我唯一能做的事情吗?谢谢。 - user782104
1
imagepng 的默认“quality”设置(应该被命名为压缩,因为 png 的压缩是无损的)是9(据我所知,我测试了没有设置质量(234个字节),质量0(几百KB)和设置为9(234个字节))。所以我想这是GD能做到的最好的。 - max-m
这会使我的黑线消失。 - Mladen Janjetovic

8

请参考以下内容:

这个示例函数可以复制透明的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");
    ?>

2

1)您可以创建一个没有现有文件的新png文件。 2)由于使用了imagecreatetruecolor();,所以您会得到一张黑色图片。它创建了一个具有黑色背景的最高质量图像。如果您需要最低质量的图像,请使用imagecreate();

<?php
$tt_image = imagecreate( 100, 50 ); /* width, height */
$background = imagecolorallocatealpha( $tt_image, 0, 0, 255, 127 ); /* In RGB colors- (Red, Green, Blue, Transparency ) */
header( "Content-type: image/png" );
imagepng( $tt_image );
imagecolordeallocate( $background );
imagedestroy( $tt_image );
?>

您可以在此文章中阅读更多信息:如何使用PHP创建图像


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接