使用PHP创建一个透明的png文件


Create a transparent png file using PHP

目前我想创建一个质量最低的透明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: 第4行上的''DPSadmin''DEV''ajax_optipng1.5''create.php

  2. 虽然有错误消息,但它仍然生成了一个png文件,然而,我发现这个文件是一个黑色的图像,我需要指定任何参数来使它透明吗?

谢谢。

到1)CCD_ 1尝试打开文件CCD_。

至2)为了能够保存阿尔法通道,使用了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');

看看:

  • imagecolorallocatelpha
  • 图像填充

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

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 创建图像