imagecolorallocate
为图像分配颜色
PHP 版本 4.3.0 及以上。
imagecolorallocate 函数为图像分配一个颜色,并返回该颜色的标识符。此函数可以用于为图像对象设置颜色,通常与 GD 库一起使用,用于创建动态图片或修改现有图像。
imagecolorallocate(resource $image, int $red, int $green, int $blue): int
返回分配的颜色标识符(一个整数)。如果颜色分配失败,返回 FALSE。
以下是一个使用 imagecolorallocate 函数创建图像并设置颜色的示例:
$image = imagecreate(100, 100); // 创建一个 100x100 像素的空白图像 $color = imagecolorallocate($image, 255, 0, 0); // 为图像分配红色 (255, 0, 0) imagesetpixel($image, 50, 50, $color); // 在图像的中心点 (50, 50) 设置像素为红色 <p>header('Content-Type: image/png'); // 设置响应头,告知浏览器图片类型<br> imagepng($image); // 输出图像为 PNG 格式<br> imagedestroy($image); // 释放图像资源<br>
在上述代码中,首先创建了一个 100x100 像素的图像,并分配了一个红色 (255, 0, 0)。接着,通过 imagesetpixel 在图像的中心设置一个红色的像素点。最后,通过 imagepng 输出图像,并使用 imagedestroy 释放资源。