Reputation:
I've tried two different images and still get the alpha/transparency replaced by black:
The original code used imagejpeg
which I've commented out b.c. jpegs do not support transparency and replaced by imagepng
.
Here are my original test images that contains alpha:
Here is the solution I tested from php.net. Actually this distorts black and white images /w alpha background.
private function imageCreateTransparent($x, $y) {
$imageOut = imagecreatetruecolor($x, $y);
$colourBlack = imagecolorallocate($imageOut, 0, 0, 0);
imagecolortransparent($imageOut, $colourBlack);
return $imageOut;
}
Upvotes: 2
Views: 153
Reputation: 116110
After some attempts, it turns out that using imagefill does work with alpha, but you need to call imagesavealpha
as well.
The final code will look like this if you wrap it in a function.
function imagecreatealpha($width, $height)
{
// Create a new image
$i = imagecreatetruecolor($width, $height);
// for when you convert to a file
imagealphablending($i, true);
imagesavealpha($i, true);
// Fill it with transparent color (translucent black in this case)
imagefill($i, 0, 0, 0xff000000);
return $i;
}
Then use it like this:
$i = imagecreatealpha(500, 500);
// Further processing goes here
// Output
header('Content-type: image/png');
imagepng($i);
The same applies to loading png images with alpha transparency in it. Oddly enough PHP doesn't do this automatically:
Upvotes: 3
Reputation: 9142
You need to call the imagesavealpha
and imagealphablending
functions.
See: http://www.php.net/manual/en/function.imagesavealpha.php first example.
Upvotes: 2