How to create an image with transparent background using PHP

If you would like to create a transparent background image using PHP then you can do so by using the GD library available in PHP by default. PHP provides the imagecolorallocatealpha function which allows you to set the transparency of the background. To use this function you also need to add 2 lines before it.

imagealphablending($image, true);
imagesavealpha($image, true);

Once you have added theses lines you will be able to generate image with transparent background.

$image = imagecreatetruecolor(700, 300);
imagealphablending($image, true);
imagesavealpha($image, true);
$bgcolor = imagecolorallocatealpha($image, 0, 0, 0, 127);
imagefill($image, 0, 0, $bgcolor);
imagestring($image,2, 100, 150, 'Text written on transparent background', $text_color);

Check out the following image generated using this process.

Image with transparent background using PHP

If we make minor changes to the code above like adding a background color and removing the transparency from the image we will get the following image.

Image without transparent background using PHP

Download the full PHP code here

Be the first to comment

Leave a Reply