note 52080 deleted from function.imagecolortransparent by cmb
| From: | cmb@php.net | Date: | Sun, 01 Dec 2019 08:48:43 +0000 |
| Subject: | note 52080 deleted from function.imagecolortransparent by cmb | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-213321@lists.php.net to get a copy of this message | ||
Note Submitter: thomas at nindel dot net
----
I wanted to have non-rectangular images being displayed on various website-backgrounds. piece of
cake with png-24 and sane browsers, but not with IE. GIF-files are useless since they tend to have
ugly edges.
So that's what i came up with, a script to merge a given PNG-24 against a background-image. The
script only merges areas of partial transparency (think anti-aliased edges) of the PNG onto the
background-image, leaving 100% transparent areas as they are. output is a 256-color gif with
transparency.
<?PHP
function alphaishMerge(&$img_unten, &$img_oben, &$transCol) {
$sx = imagesx($img_unten);
$sy = imagesy($img_oben);
// just be sure
imagealphablending($img_unten, TRUE);
imagealphablending($img_oben, TRUE);
// imagecopy respects alpha channels
imagecopy($img_unten, $img_oben, 0, 0, 0, 0, $sx, $sy);
for ($x = 0; $x < $sx; $x++) {
for ($y = 0; $y < $sy; $y++) {
// get RGBA of upper image
$pxloben = imagecolorat($img_oben, $x, $y);
$pxloben = imagecolorsforindex($img_oben, $pxloben);
if ($pxloben['alpha'] == 127) {
// if this pixel is fully transparent...
// ...set it to the transparent color
imagesetpixel($img_unten,$x,$y,$transCol);
}
}
}
}
// images have to be the same size
$bg_file = "background.jpg";
$png_file ="kauscha.png";
// background-image (jpg)
$img_bg = imagecreatefromjpeg($bg_file);
// image which is supposed to be put on the background (PNG-24)
$img_png = imagecreatefrompng($png_file);
// This color is the one getting transparent in the gif-file
$transCol = imagecolorallocate($img_bg, 0, 0, 0);
// magic
alphaishMerge($img_bg, $img_png, $transCol);
// reduce color depth
imagetruecolortopalette($img_bg, FALSE, 255);
// make it transparent
$transCol = imagecolortransparent($img_bg, $transCol);
header("Content-type: image/gif");
imagegif($img_bg);
?>
i hope thats useful for anyone.