9951 explained code solutions for 126 technologies


php-gdHow to create transparent background


Here we'll draw black filled circle on a transparent background:

<?php

$im = imagecreatetruecolor(400, 300);

imagealphablending($im, false);
$tr = imagecolorallocatealpha($im, 0, 0, 0, 255);
imagefill($im, 0, 0, $tr);
imagesavealpha($im, true);

$c_black = imageColorAllocate($im, 0,0,0);
imagefilledellipse($im, 200, 150, 100, 100, $c_black);

imagePng($im, '/tmp/image.png');ctrl + c
imagecreatetruecolor

creates true color GD image object with specified width & height

imagealphablending

we're disabling alpha blending to prevent transparent background being converted to black color

imagecolorallocatealpha

creates color with transparency (in our case, we just create fully transparent color)

imagefill(

fills an entire image with a given color (transparent "color" in our case)

imageColorAllocate

creates color object to later use in image

imagefilledellipse

creates ellipse with specified coordinates, radius and color

imagePng

saves image in PNG format to the given path


How to create transparent background, php gd

Usage example

<?php

$im = imagecreatetruecolor(400, 300);

imagealphablending($im, false);
$tr = imagecolorallocatealpha($im, 0, 0, 0, 127);
imagefill($im, 0, 0, $tr);
imagesavealpha($im, true);

$c_black = imageColorAllocate($im, 0,0,0);
imagefilledellipse($im, 200, 150, 100, 100, $c_black);

imagePng($im, '/tmp/image.png');