2
$im = imagecreatefrompng('./test.png');
$white = imagecolorallocate($im, 255, 255, 255);
imagecolortransparent($im, $white);

This code is fine for removing pure white from an image, but I what I want to do is convert all colors to alpha percentages. For example medium gray would be 50% transparent black. So an image that was medium gray would show the image behind it, if placed on top.

Is this possible using PHP or an extension?

Tim
  • 71
  • 1
  • 7

1 Answers1

0

I just wrote and tested this script for you.

$imfile = './test.png';
$origim = imagecreatefrompng($imfile);
$im_size = getimagesize($imfile);

$im = imagecreatetruecolor($im_size[0], $im_size[1]);
imagealphablending($im, false);
imagesavealpha($im, true);

for ($x = 0; $x < $im_size[0]; ++$x){
    for ($y = 0; $y < $im_size[1]; ++$y){
        $rgb = imagecolorat($origim,- $x, $y);
        $r = ($rgb >> 16) & 0xFF;
        $g = ($rgb >> 8) & 0xFF;
        $b = $rgb & 0xFF;
        $color = imagecolorallocatealpha($im, 0, 0, 0, intval(($r+$g+$b)/3/255*127)); 
        imagesetpixel($im, $x, $y, $color);
    }
}

It may be a bit slow on large images, but it works just like you want it to. =)

Hope this answer is Acceptable. Good luck.

  • 1
    If I save the image `imagepng($im,'./test2.png');` it just appears completely black. Any ideas? – Tim Jul 20 '11 at 09:10
  • Simply replace this line to get rid of the black and make it colored: `$color = imagecolorallocatealpha($im, 0, 0, 0, intval(($r+$g+$b)/3/255*127));` to.. `$color = imagecolorallocatealpha($im, $r, $b, $g, intval(($r+$g+$b)/3/255*127));` – Muhammad bin Yusrat Oct 02 '17 at 07:29