user656925
user656925

Reputation:

alpha(transparency) is replaced w/ black - why?

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:

enter image description here

enter image description here

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

Answers (2)

GolezTrol
GolezTrol

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

Rob W
Rob W

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

Related Questions