php GD创建一个透明的png图像

时间:2011-05-24 11:41:55

标签: php image transparency gd

我正在尝试创建一个透明的png图像,并将各种其他png和jpgs分层,以创建一个具有透明度的最终png。我在创建我的初始空透明png时遇到了麻烦。它目前有白色背景。

任何人都可以指出我正确的方向。到目前为止,这是我的代码......

$image = imagecreatetruecolor(485, 500);
imagealphablending($image, false);
imagesavealpha($image, true);
$col=imagecolorallocatealpha($image,255,255,255,127);
imagefill($image, 0, 0, $col);
//imagefilledrectangle($image,0,0,485, 500,$col);


/* add door glass */
$img_doorGlass = imagecreatefrompng("glass/$doorStyle/$doorGlass.png");     
imagecopyresampled($image, $img_doorGlass, 106, 15, 0, 0, 185, 450, 185, 450);              


/* add door */
$img_doorStyle = imagecreatefrompng("door/$doorStyle/$doorStyle"."_"."$doorColor.png");     
imagecopyresampled($image, $img_doorStyle, 106, 15, 0, 0, 185, 450, 185, 450);


$fn = md5(microtime()."door_builder").".png";

if(imagepng($image, "user_doors/$fn", 1)){
  echo "user_doors/$fn";
}       
imagedestroy($image);       

3 个答案:

答案 0 :(得分:30)

在每个新图层上设置imagealphablending($image,true);

试试这个:

<?php
$image = imagecreatetruecolor(485, 500);
imagealphablending($image, false);
$col=imagecolorallocatealpha($image,255,255,255,127);
imagefilledrectangle($image,0,0,485, 500,$col);
imagealphablending($image,true);

/* add door glass */
$img_doorGlass = imagecreatefrompng("glass/$doorStyle/$doorGlass.png");
imagecopyresampled($image, $img_doorGlass, 106, 15, 0, 0, 185, 450, 185, 450);
imagealphablending($image,true);

/* add door */
$img_doorStyle = imagecreatefrompng("door/$doorStyle/$doorStyle"."_"."$doorColor.png");
imagecopyresampled($image, $img_doorStyle, 106, 15, 0, 0, 185, 450, 185, 450);
imagealphablending($image,true);

$fn = md5(microtime()."door_builder").".png";

imagealphablending($image,false);
imagesavealpha($image,true);
if(imagepng($image, "user_doors/$fn", 1)){
    echo "user_doors/$fn";
}
imagedestroy($image);

?>

答案 1 :(得分:3)

此代码对我有用:

$img=imagecreatetruecolor(180,20);
imagealphablending($img,false);

$col=imagecolorallocatealpha($img,255,255,255,127);
imagefilledrectangle($img,0,0,180,20,$col);
imagealphablending($img,true);

$font=$_SERVER["DOCUMENT_ROOT"].'/fonts/Arial.ttf';
$color = imagecolorallocate($img, 140, 173, 209);
imagettftext($img,11,0,5,14,$color,$font,'Text goes here'); 

header('Content-Type: image/png');
imagealphablending($img,false);
imagesavealpha($img,true);
imagepng($img);

答案 2 :(得分:0)

尝试替换
$col=imagecolorallocatealpha($image,255,255,255,127);

$col=imagecolorallocate($image,255,255,255);

并尝试取消注释imagefilledrectangle行 我可以测试这段代码 - 给我照片:)。