Convert images to alpha transparency with PHP
$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 m开发者_如何学Cedium 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?
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.
精彩评论