1

Here my problem:

I want to change the opacity of an image, by copying it on another transparent image.

My code:

$opacity = 50;

$transparentImage = imagecreatetruecolor($width, $height);
imagesavealpha($transparentImage, true);
$transColour = imagecolorallocatealpha($transparentImage , 0, 0, 0, 127);
imagefill($transparentImage , 0, 0, $transColour);

imagecopymerge($transparentImage, $image, 0, 0, 0, 0, $width, $height, $opacity);

$image = $transparentImage;

header('Content-type: image/png');
imagepng($image);

By doing this, when I use imagecopymerge, $transparentImage loses its transparency... So $image is merged on a black image... and not on a transparent image !

However, when I show $transparentImage before calling imagecopymerge, the image is transparent in my navigator !

Is there a solution to change opacity of my image, without adding it on a colored background ?

Sybio
  • 8,565
  • 3
  • 44
  • 53

1 Answers1

1

It seems that imagecopymerge does not support the alpha (transparency) channel on images. Fortunately you can use a workaround with imagecopy to do it correctly. Here's a function to do this, taken from the comments on php.net:

function imagecopymerge_alpha($dst_im, $src_im, $dst_x, $dst_y, $src_x, $src_y, $src_w, $src_h, $pct){
    // creating a cut resource
    $cut = imagecreatetruecolor($src_w, $src_h);

    // copying relevant section from background to the cut resource
    imagecopy($cut, $dst_im, 0, 0, $dst_x, $dst_y, $src_w, $src_h);

    // copying relevant section from watermark to the cut resource
    imagecopy($cut, $src_im, 0, 0, $src_x, $src_y, $src_w, $src_h);

    // insert cut resource to destination image
    imagecopymerge($dst_im, $cut, $dst_x, $dst_y, 0, 0, $src_w, $src_h, $pct);
} 
Jon
  • 428,835
  • 81
  • 738
  • 806
  • Hello, in fact I want to preserve the transparency of my $dst_im, which is transparent, and not just the transparency of $src_im :( – Sybio Mar 04 '12 at 15:46