函数名:imagecolortransparent()
适用版本:PHP 4, PHP 5, PHP 7
用法:imagecolortransparent() 函数将图像中的特定颜色设置为透明色,使得该颜色在图像显示时变为透明的。该函数在使用 GIF 或 PNG 图像时特别有用,可以为图像创建透明背景。
语法:bool imagecolortransparent ( resource $image , int $color )
参数:
- $image:图像资源,通过 imagecreatefromjpeg()、imagecreatefrompng() 等函数创建。
- $color:要设置为透明的颜色索引。颜色索引是一个从 0 到 255 的整数,取决于图像的调色板。
返回值:成功时返回 true,失败时返回 false。
示例:
// 创建一个 200x200 像素的图像
$image = imagecreatetruecolor(200, 200);
// 创建一个红色
$red = imagecolorallocate($image, 255, 0, 0);
// 填充图像背景为红色
imagefill($image, 0, 0, $red);
// 将红色设置为透明色
imagecolortransparent($image, $red);
// 创建一个绿色
$green = imagecolorallocate($image, 0, 255, 0);
// 在图像上绘制一个绿色的矩形
imagefilledrectangle($image, 50, 50, 150, 150, $green);
// 在浏览器中显示图像
header('Content-type: image/png');
imagepng($image);
imagedestroy($image);
在上述示例中,首先创建了一个 200x200 像素的图像,并将背景填充为红色。然后使用 imagecolortransparent() 函数将红色设置为透明色。最后,使用 imagefilledrectangle() 函数在图像上绘制一个绿色的矩形。通过在浏览器中显示图像,可以看到矩形部分是绿色的,而背景部分是透明的。