Alex
Alex

Reputation: 1398

How to make an image itself Transparent/Alpha with GD?

In PHP GD, is it possible to make an image it-self transparent? I'm not talking about the background, etc. Is it possible to take a PNG image, and make the image transparent?

For example:

$c = imagecreatefrompng($urlToImage);
imagefill($c, 0, 0, imagecolorallocatealpha($c, 255, 255, 255, 50)); // 50 alpha.

imagepng($c);

This, however, doesn't do anything. Is there something I am missing? Thank you.

Upvotes: 0

Views: 237

Answers (1)

Vit Kos
Vit Kos

Reputation: 5755

You forgot to use imagecolortransparent() function. more at : http://www.php.net/manual/en/function.imagecolortransparent.php

Taken from comments there here is an example of adding transparency

if($transparency) {
        if($ext=="png") {
            imagealphablending($new_img, false);
            $colorTransparent = imagecolorallocatealpha($new_img, 0, 0, 0, 127);
            imagefill($new_img, 0, 0, $colorTransparent);
            imagesavealpha($new_img, true);
        } elseif($ext=="gif") {
            $trnprt_indx = imagecolortransparent($img);
            if ($trnprt_indx >= 0) {
                //its transparent
                $trnprt_color = imagecolorsforindex($img, $trnprt_indx);
                $trnprt_indx = imagecolorallocate($new_img, $trnprt_color['red'], $trnprt_color['green'], $trnprt_color['blue']);
                imagefill($new_img, 0, 0, $trnprt_indx);
                imagecolortransparent($new_img, $trnprt_indx);
            }
        }
    } else {
        Imagefill($new_img, 0, 0, imagecolorallocate($new_img, 255, 255, 255));
    }

Upvotes: 1

Related Questions