Voting

: nine minus three?
(Example: nine)

The Note You're Voting On

dscharrer at gmail dot com
20 years ago
If imagealphablending os set to true and you want to merge two images, you are left with no transparency. If it is set to false, only the transparency of the second image is respected, causing no parts of the first image to be shown. To solve this use the following function:

<?
//Merge multiple images and keep transparency

//$i is and array of the images to be merged:
// $i[1] will be overlayed over $i[0]
// $i[2] will be overlayed over that
// ...

//the function returns the resulting image ready for saving

function imagemergealpha($i) {

//create a new image
$s = imagecreatetruecolor(imagesx($i[0]),imagesy($i[1]));

//merge all images
imagealphablending($s,true);
$z = $i;
while($d = each($z)) {
imagecopy($s,$d[1],0,0,0,0,imagesx($d[1]),imagesy($d[1]));
}

//restore the transparency
imagealphablending($s,false);
$w = imagesx($s);
$h = imagesy($s);
for($x=0;$x<$w;$x++) {
for($y=0;$y<$h;$y++) {
$c = imagecolorat($s,$x,$y);
$c = imagecolorsforindex($s,$c);
$z = $i;
$t = 0;
while($d = each($z)) {
$ta = imagecolorat($d[1],$x,$y);
$ta = imagecolorsforindex($d[1],$ta);
$t += 127-$ta['alpha'];
}
$t = ($t > 127) ? 127 : $t;
$t = 127-$t;
$c = imagecolorallocatealpha($s,$c['red'],$c['green'],$c['blue'],$t);
imagesetpixel($s,$x,$y,$c);
}
}
imagesavealpha($s,true);
return $s;
}
?>

<< Back to user notes page

To Top