user3790770
user3790770

Reputation: 83

PHP image creation - problems with opacity

I need help with setting opacity correctly. Basically, I have a banner (a rectangle) with certain user defined color. And over that I would like to insert a png image of a flag, which is round and has transparent background.

However when I overlay them, they still show white background where it should be transparent. I tried saving the alpha and went through several threads here on stackoverflow, but nothing worked...

Here is my code:

$width = 800;
$height = 150;

$png_image = imagecreate($width, $height);
imagealphablending( $png_image, true );
imagesavealpha( $png_image, true );
$bg = imagecolorallocate($png_image, hex2rgb($color_schemes[$design]['900'])[0], hex2rgb($color_schemes[$design]['900'])[1], hex2rgb($color_schemes[$design]['900'])[2]);

$icon1 = imagecreatefrompng('../../imgs/flags/big/us.png');
imagealphablending( $icon1, true );
imagesavealpha( $icon1, true );
imagecopy($png_image, $icon1, 10, 10, 0, 0, 80, 80);

There is some other stuff in the image as well, but that is not relevant to this issue. The result of the above is this: http://www.meteotemplate.com/template/plugins/banner/bannerCreate.php

And you can see the flag being surrounded by the white background even though the PNG image is transparent around the flag...

Upvotes: 0

Views: 77

Answers (1)

spenibus
spenibus

Reputation: 4409

Use imagecreatetruecolor() instead of imagecreate().

While the php docs are surprisingly unclear about this, imagecreatetruecolor() creates a RGBA image, which is necessary for having alpha transparency.

PHP Docs http://php.net/manual/en/function.imagecreatetruecolor.php

Note

The color indexes are 32bit ARGB, if for some reason you decided to create them directly rather than allocate them. This is actually quite convenient.

Bonus: ARGB color function

// return 32bit ARGB color index
// input red (0-255), green (0-255), blue(0-255), alpha (0-127)
function makeColor($r=0, $g=0, $b=0, $a=0) {
   return ($a << 24) + ($r << 16) + ($g << 8) + $b;
}

Upvotes: 2

Related Questions