函数名:imagecolorallocate()
适用版本:PHP 4, PHP 5, PHP 7
用法:imagecolorallocate() 函数在调色板中为图像分配一个颜色,该函数返回一个表示颜色的标识符。
语法:imagecolorallocate(image $image, int $red, int $green, int $blue)
参数:
- $image:图像资源(由 imagecreate() 或 imagecreatetruecolor() 创建)
- $red:红色分量的值(0-255)
- $green:绿色分量的值(0-255)
- $blue:蓝色分量的值(0-255)
返回值:成功时返回一个表示颜色的标识符,失败时返回 FALSE。
示例:
// 创建一个 200x200 的空白图像
$image = imagecreatetruecolor(200, 200);
// 分配一个白色
$white = imagecolorallocate($image, 255, 255, 255);
// 在图像上绘制一个红色的矩形
imagefilledrectangle($image, 50, 50, 150, 150, imagecolorallocate($image, 255, 0, 0));
// 在图像上写入文本
$text_color = imagecolorallocate($image, 0, 0, 0);
imagestring($image, 5, 80, 80, 'Hello, PHP!', $text_color);
// 输出图像到浏览器
header('Content-type: image/png');
imagepng($image);
// 释放内存
imagedestroy($image);
以上示例中,我们首先创建了一个空白图像,然后使用 imagecolorallocate() 函数分配了一个白色。接着,我们使用 imagefilledrectangle() 函数在图像上绘制了一个红色的矩形,并使用 imagestring() 函数在图像上写入了文本。最后,我们使用 imagepng() 函数将图像输出到浏览器,并使用 imagedestroy() 函数释放了内存。