繁体   English   中英

将2个透明的PNG图像与PHP GD库合并

[英]Merge 2 transparent PNG images with PHP GD library

我正在尝试合并两个透明的PNG图像。 第二个PNG图像应具有50%的不透明度。

问题:

如果第二个PNG仅覆盖第一个PNG的非透明像素,则一切正常。

如果第二个PNG具有覆盖第一个PNG的透明像素的区域,则这些区域将变为黑色。

编码:

<?php

function imagecopymerge_alpha($dst_im, $src_im, $dst_x, $dst_y, $src_x, $src_y, $src_w, $src_h, $pct){ 
    $cut = imagecreatetruecolor($src_w, $src_h);
    imagecopy($cut, $dst_im, 0, 0, $dst_x, $dst_y, $src_w, $src_h); 
    imagecopy($cut, $src_im, 0, 0, $src_x, $src_y, $src_w, $src_h); 
    imagecopymerge($dst_im, $cut, $dst_x, $dst_y, 0, 0, $src_w, $src_h, $pct); 
}

$image1 = imagecreatefrompng('a.png'); //300 x 300
$image2 = imagecreatefrompng('b.png'); //150 x 150

$merged_image = imagecreatetruecolor(300, 300);
imagealphablending($merged_image, false);
imagesavealpha($merged_image, true);

imagecopy($merged_image, $image1, 0, 0, 0, 0, 300, 300);
imagecopymerge_alpha($merged_image, $image2, 0, 0, 0, 0, 150, 150, 50);

header('Content-Type: ' . image_type_to_mime_type(IMAGETYPE_PNG));
imagepng($merged_image);

?>

如果您尝试这样做呢? 这个对我有用。

<?php

$image1 = imagecreatefrompng('a.png'); //300 x 300
$image2 = imagecreatefrompng('b.png'); //150 x 150
$merged_image = imagecreatetruecolor(300, 300);

// DEFINE MAGENTA AS THE TRANSPARENCY COLOR AND FILL THE IMAGE FIRST
$transparentColor = imagecolorallocate($merged_image, 255, 0, 255); 
imagecolortransparent($merged_image, $transparentColor);
imagefill($merged_image, 0, 0, $transparentColor);

imagesavealpha($merged_image, true);

imagealphablending($image1, false);
imagecopyresampled($merged_image, $image1, 0, 0, 0, 0, 300, 300, 300, 300);
imagealphablending($image1, true);
imagedestroy($image1); // FREE UP SOME MEMORY

imagealphablending($image2, false);
imagecopyresampled($merged_image, $image2, 0, 0, 0, 0, 300, 300, 150, 150);
imagealphablending($image2, true);
imagedestroy($image2); // FREE UP SOME MEMORY

imagealphablending($merged_image, false);
imagesavealpha($merged_image, true);

header('Content-Type: ' . image_type_to_mime_type(IMAGETYPE_PNG));
imagepng($merged_image);

?>

我花了很多时间对此进行实验。 希望这对您或可能偶然发现此问题的其他人有所帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM