首页 话题 小组 问答 好文 用户 我的社区 域名交易 唠叨

[函数]imagecolorallocate()函数—用法及示例

发布于 2025-04-27 14:23:18
0
18

函数名: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() 函数释放了内存。

评论
一个月内的热帖推荐
啊龙
Lv.1普通用户

9545

帖子

31

小组

3242

积分

赞助商广告
站长交流