php 实现图片透明
使用 imagecolorallocatealpha 函数创建透明颜色
在 PHP 中,可以使用 imagecolorallocatealpha 函数为图像分配一个包含透明度(alpha)值的颜色。该函数的第四个参数即为透明度,范围从 0(不透明)到 127(完全透明)。
$image = imagecreatetruecolor(200, 200);
$transparent = imagecolorallocatealpha($image, 0, 0, 0, 127);
imagefill($image, 0, 0, $transparent);
保存 PNG 图像时保留透明度
当处理透明图像时,必须将图像保存为 PNG 格式,因为 PNG 支持 alpha 通道透明度。使用 imagesavealpha 函数确保透明度信息被保留。
imagesavealpha($image, true);
imagepng($image, 'transparent.png');
imagedestroy($image);
使现有图像部分区域透明
对于已有图像,可以通过设置特定颜色为透明来实现透明效果。使用 imagecolortransparent 函数将图像中的某种颜色设为透明。
$image = imagecreatefrompng('example.png');
$transparent_color = imagecolorallocate($image, 255, 255, 255);
imagecolortransparent($image, $transparent_color);
imagepng($image, 'transparent_output.png');
创建透明背景的圆形或形状
在绘制透明形状时,需要先创建一个透明画布,然后使用 imagefilledellipse 或其他绘图函数绘制形状。
$image = imagecreatetruecolor(200, 200);
$transparent = imagecolorallocatealpha($image, 0, 0, 0, 127);
imagefill($image, 0, 0, $transparent);
$red = imagecolorallocatealpha($image, 255, 0, 0, 50);
imagefilledellipse($image, 100, 100, 150, 150, $red);
合并透明图像
使用 imagecopymerge 或 imagecopyresampled 函数合并图像时,可以通过设置 merge 参数来控制透明度。
$dst = imagecreatefrompng('background.png');
$src = imagecreatefrompng('transparent_layer.png');
imagecopymerge($dst, $src, 0, 0, 0, 0, 200, 200, 50); // 50% 透明度
imagepng($dst, 'merged.png');
注意事项
- 透明效果仅在 PNG 格式中有效,JPEG 不支持透明度。
- 确保在调用
imagepng之前设置imagesavealpha(true)。 - 透明颜色的 alpha 值范围是 0-127,与 CSS 中的 0-255 不同。
- 处理完图像后使用
imagedestroy释放内存。







