Shayka
Shayka

Reputation: 49

How to create transparent background with PHP using GD?

I made an image combining 3 different images, but I need a transparent background, and I don't succeed doing it. This is my final code:

<?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);

?>

and the results is: click here

Upvotes: 0

Views: 8703

Answers (2)

digout
digout

Reputation: 4252

Try using

imagecolortransparent($im);

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

Upvotes: 2

Marc B
Marc B

Reputation: 360702

You're not telling GD to use alpha in any of your code. That's done with imagesavealpha, imagealphablending, etc...

Upvotes: 3

Related Questions