How to create an image with GDlib with a transparent background?
header('content-type: image/png');
$image = imagecreatetruecolor(900, 350);
imagealphablending($image, true);
imagesavealpha($image, true);
$text_color = imagecolorallocate($image, 0, 51, 102);
imagestring($image,2,4,4,'Test',$text_color);
imagepng($image);
imagedestroy($image);
Here the background is black
The benefit of PNG images is that they have the capability for transparency. Use the remove background tool to create a transparent background for an image, headshot, or logo, which you can then place into a variety of new designs and destinations.
The JPEG format doesn't support transparency. But we can create our own transparency using a second image as an alpha channel. Since this image is simple and monochromatic, it compresses extremely well: ours came out to just 11K.
Something like this...
$im = @imagecreatetruecolor(100, 25);
# important part one
imagesavealpha($im, true);
imagealphablending($im, false);
# important part two
$white = imagecolorallocatealpha($im, 255, 255, 255, 127);
imagefill($im, 0, 0, $white);
# do whatever you want with transparent image
$lime = imagecolorallocate($im, 204, 255, 51);
imagettftext($im, $font, 0, 0, $font - 3, $lime, "captcha.ttf", $string);
header("Content-type: image/png");
imagepng($im);
imagedestroy($im);
Add a line
imagefill($image,0,0,0x7fff0000);
somewhere before the imagestring
and it will be transparent.
0x7fff0000
breaks down into:
alpha = 0x7f
red = 0xff
green = 0x00
blue = 0x00
which is fully transparent.
This should work:
$img = imagecreatetruecolor(900, 350);
$color = imagecolorallocatealpha($img, 0, 0, 0, 127); //fill transparent back
imagefill($img, 0, 0, $color);
imagesavealpha($img, true);
This should work. It has worked for me.
$thumb = imagecreatetruecolor($newwidth,$newheight);
$transparent = imagecolorallocatealpha($thumb, 0, 0, 0, 127);
imagefill($thumb, 0, 0, $transparent);
imagesavealpha($thumb, true);
imagecopyresampled($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
imagepng($thumb, $output_dir);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With