2013-06-24 58 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是透明的顏色。