使用PHP创建透明的png文件

use*_*104 13 php png image 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');
?>
Run Code Online (Sandbox Code Playgroud)

但是,有一些问题:

  1. 在创建任何新文件之前,我是否需要特定一个png文件?或者我可以创建没有任何现有的png文件?

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

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

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

谢谢.

max*_*x-m 36

要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');
Run Code Online (Sandbox Code Playgroud)


neu*_*se7 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");
    ?>
Run Code Online (Sandbox Code Playgroud)