Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create an image with transparent background

Tags:

php

gdlib

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

like image 275
clarkk Avatar asked Dec 08 '11 21:12

clarkk


People also ask

Can you make a PNG with transparent background?

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.

Can a JPEG have a transparent background?

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.


4 Answers

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);
like image 131
Dejan Marjanović Avatar answered Oct 06 '22 23:10

Dejan Marjanović


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.

like image 38
mvds Avatar answered Oct 07 '22 00:10

mvds


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);
like image 29
Okochea Avatar answered Oct 06 '22 23:10

Okochea


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);
like image 31
Faisal Rehman Avatar answered Oct 07 '22 00:10

Faisal Rehman