When using the function imagepng()
in PHP, how can I make sure the images that I save are saved with a transparent background?
Asked
Active
Viewed 4.3k times
20

Giacomo1968
- 25,759
- 11
- 71
- 103

Strawberry
- 66,024
- 56
- 149
- 197
4 Answers
56
Simply do this:
imagealphablending($img, false);
imagesavealpha($img, true);
Before outputting. Make sure that all source files (if you used any) are set to PNG 32-bit with transparency - if not the output may differ with black background or transparency does not comply.

mauris
- 42,982
- 15
- 99
- 131
-
Transparency is often called "alpha". – Ewan Todd Nov 10 '09 at 01:40
-
1The accepted solution didn't worked as expected, but this one is perfect! – testing Oct 06 '11 at 12:15
-
1Yep, after the above solution from Eric didn't really do anything, this worked right off the bat. – Anriëtte Myburgh Oct 20 '14 at 08:28
-
Another question is, [how to save the output image into a different directory, with a new filename and extension?](http://stackoverflow.com/q/30331812/4883372) – 5ervant - techintel.github.io May 19 '15 at 23:58
18
Here is the example
$newimage = imagecreatetruecolor($dst_w, $dst_h);
imagealphablending($newimage, false);
imagesavealpha($newimage, true);
$transparentindex = imagecolorallocatealpha($newimage, 255, 255, 255, 127);
imagefill($newimage, 0, 0, $transparentindex);

user2731504
- 187
- 1
- 3
10
Here is an example of the imagecolortransparent
function (if it helps):
<?php
// Create a 55x30 image
$im = imagecreatetruecolor(55, 30);
$red = imagecolorallocate($im, 255, 0, 0);
$black = imagecolorallocate($im, 0, 0, 0);
// Make the background transparent
imagecolortransparent($im, $black);
// Draw a red rectangle
imagefilledrectangle($im, 4, 4, 50, 25, $red);
// Save the image
imagepng($im, './imagecolortransparent.png');
imagedestroy($im);
?>

Giacomo1968
- 25,759
- 11
- 71
- 103

Eric
- 757
- 5
- 11
-
1Eric beat me to it here. Later on the same page, someone comments, "When you use palette images (created with imagecreate()), the first color allocated is the background color. This color cannot be used for transparency. So if you want to make the background transparent, first allocate a dummy background color, then allocate the real background color and declare this is as transparent." – Ewan Todd Nov 10 '09 at 01:38
0
There's a function called imagecolortransparent that allows you to set which color is made transparent. I don't know if this answers your question.

lamelas
- 872
- 6
- 15