如何使用GD创建透明背景?

时间:2011-11-09 16:01:44

标签: php transparency gd

我制作了一个图像,结合了3个不同的图像,但我需要一个透明的背景,而且我没有成功。这是我的最终代码:

<?php

$meko = $_GET['image'];
$im = $meko;
$bookback = "images/book_back.png";
$mekoCanvas = imagecreatetruecolor(115, 135);
$canvas = imagecreatetruecolor(115, 185);

$bookback = imagecreatefrompng($bookback);
$meko = imagecreatefromjpeg($meko);

imagecopy($mekoCanvas, $meko, 0, 0, 0, 0, 100, 135);
imagecopy($mekoCanvas, $bookback, 100, 0, 0, 0, 15, 135);

$im = $mekoCanvas;
$rH = 50; // Reflection height
$tr = 30; // Starting transparency
$div = 1; // Size of the divider line
$w = 115;
$h = 135;
//$im = imagecreatefromjpeg($im);
$li = imagecreatetruecolor($w, 1);
$bgc = imagecolorallocate($li, 255, 255, 255); // Background color
imagefilledrectangle($li, 0, 0, $w, 1, $bgc);
$bg = imagecreatetruecolor($w, $rH);
$wh = imagecolorallocate($im,255,255,255);

$im = imagerotate($im, -180, $wh);
imagecopyresampled($bg, $im, 0, 0, 0, 0, $w, $h, $w, $h);
$im = $bg;
$bg = imagecreatetruecolor($w, $rH);
for ($x = 0; $x < $w; $x++) {
    imagecopy($bg, $im, $x, 0, $w-$x, 0, 1, $rH);
}
$im = $bg;

$in = 100/$rH;
for($i=0; $i<=$rH; $i++){
    if($tr>100) $tr = 100;
    imagecopymerge($im, $li, 0, $i, 0, 0, $w, 1, $tr);
    $tr+=$in;
}
imagecopymerge($im, $li, 0, 0, 0, 0, $w, $div, 100); // Divider
header('content-type: image/jpeg');

imagecopy($canvas, $mekoCanvas, 0, 0, 0, 0, 115, 135);
imagecopy($canvas, $im, 0, 135, 0, 0, 115, 50);

imagejpeg($canvas);

imagedestroy($im);
imagedestroy($li);

?>

结果是: click here

2 个答案:

答案 0 :(得分:3)

你并没有告诉GD在你的任何代码中使用alpha。这是通过imagesavealphaimagealphablending等完成的。

答案 1 :(得分:2)

尝试使用

imagecolortransparent($im);

http://www.php.net/manual/en/function.imagecolortransparent.php