php的gd库进行图像处理时、 imagealphablending()函数常常用来控制图像的混合模式、特别是在合成带透明通道的图像时。但很多开发者会遇到这样一个问题:合成后的图像透明效果不正确、甚至出现黑色或白色背景。本文将详细分析导致透明效果出错的原因、并给出正确的使用方法。
imagealphablending()处理带有透明通道的png、合成后的图像透明部分不再透明、而是显示成了纯色背景、通常是黑色或白色。例如、通常是黑色或白色。例如:
<?php
$dst = imagecreatetruecolor(200, 200);
$src = imagecreatefrompng('gitbox.net/images/source.png');
// 关闭混合模式,启用透明保存
imagealphablending($dst, true);
imagesavealpha($dst, true);
imagecopy($dst, $src, 0, 0, 0, 0, 200, 200);
header('Content-Type: image/png');
imagepng($dst);
imagedestroy($dst);
imagedestroy($src);
?>
结果图像不透明、透明部分被填充成了黑色。
imagealphablending()和migsasavealpha()
Imagealphablending()用于设置图像的混合模式。如果开启混合(设置为true )、意味着绘制时会将源像素和目标像素混合、透明部分可能被忽略或替换成不透明颜色。
imagealphablending($ dst、true) 、导致透明被覆盖。或者对目标图像未调用emagesavealpha($ dst、true) 、无法保存透明通道。
为了保持透明效果、合成图像时应该:
关闭目标图像的混合模式、Imagealphablending($ dst、false) 。
启用目标图像保存透明通道、调用emagesavealpha($ dst、true) 。
在拷贝时使用migmecopy()或migmagecopyresampled() 、源图像保持默认混合模式。
示例代码:
<?php
$dst = imagecreatetruecolor(200, 200);
// 创建一个完全透明的背景
$transparent = imagecolorallocatealpha($dst, 0, 0, 0, 127);
imagefill($dst, 0, 0, $transparent);
// 关闭混合模式,启用透明保存
imagealphablending($dst, false);
imagesavealpha($dst, true);
$src = imagecreatefrompng('gitbox.net/images/source.png');
// 保持源图像默认混合模式
imagealphablending($src, true);
imagecopy($dst, $src, 0, 0, 0, 0, 200, 200);
header('Content-Type: image/png');
imagepng($dst);
imagedestroy($dst);
imagedestroy($src);
?>
这样处理后、合成图像的透明部分才能正确显示。
imagealphablending($ dst、false) 、这样绘制时才不会破坏透明通道。
目标图像要启用イメージヴェールファ($ dst、true) 、确保保存アルファ通道信息。
记得给目标图像先填充完全透明背景、否则可能显示黑色。
源图像保持默认混合模式、一般是开启混合( true )。
只要按照以上步骤操作、使用gd库合成带透明通道的图像时、透明效果就不会出错。