2013-06-24 59 views
6

目前我想创建一个质量最低的透明png文件。使用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无这样的文件或目录:\ DSPadmin \ DEV \ ajax_optipng1.5 \ create.php第4行

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

谢谢。

回答

25

至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'); 
+0

感谢您的帮助!你介意教我如何最小化PNG文件的大小?imagepng函数中设置'9'质量级别是我能做的唯一事情吗?谢谢 – user782104

+1

'imagepng'默认的“质量”设置(应该命名为压缩,因为'png的压缩是无损的)是9(afaik,我测试没有设置质量(234'Bytes'),质量为0百KB')和设置9(234字节))。所以我想这是GD能做的最好的。 –

+0

这使我的黑线消失 –

5

看看:

一个例子功能复制透明的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); 
?> 

你可以阅读更多的这篇文章在:How to Create an Image Using PHP

1

您可以使用控制台实用convert是ImageMagick的一部分 - 在大多数Linux回购和自制可用为OSX:

exec('convert image.png -transparent black image_transparent.png') 

在这个例子中black是透明的颜色。