使用PHP创建透明的png文件

时间:2013-06-24 09:06:27

标签: php image png imagecreatefrompng

目前我想创建一个质量最低的透明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):无法打开流:

    中没有此类文件或目录 第4行的

    C:\ DSPadmin \ DEV \ ajax_optipng1.5 \ create.php

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

  3. 感谢。

3 个答案:

答案 0 :(得分:35)

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

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

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

答案 1 :(得分:7)

看看:

示例函数复制透明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 :(得分: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 );
?>

您可以在本文中阅读更多内容:How to Create an Image Using PHP