php imagefill
时间: 2023-07-26 22:31:49 浏览: 55
`imagefill()` 是 PHP GD 图形处理库中的一个函数,用于向指定的图像填充颜色。
函数原型如下:
```
bool imagefill ( resource $image , int $x , int $y , int $color )
```
参数说明:
- `$image`:图像资源标识符,由 `imagecreate()` 等函数返回。
- `$x`:填充的起始点 x 坐标。
- `$y`:填充的起始点 y 坐标。
- `$color`:填充的颜色,可以是颜色标识符(如 `IMG_COLOR_TOT`)或 RGB 值(如 `0xFF0000` 表示红色)。
函数返回值:
- 如果成功则返回 `true`,否则返回 `false`。
示例代码:
```php
<?php
// 创建一个 200 x 200 的画布
$im = imagecreate(200, 200);
// 设置填充颜色为红色(RGB 值为 0xFF0000)
$fill_color = imagecolorallocate($im, 0xFF, 0x00, 0x00);
// 向画布指定的位置填充颜色
imagefill($im, 0, 0, $fill_color);
// 输出图像
header('Content-type: image/png');
imagepng($im);
// 释放资源
imagedestroy($im);
?>
```
相关问题
PHP 生成验证码
PHP 生成验证码可以使用 GD 库来实现,以下是一个简单的示例:
```php
<?php
session_start();
// 生成随机字符串
$code = substr(md5(mt_rand()), 0, 4);
// 保存验证码到 session
$_SESSION['captcha'] = $code;
// 创建画布
$image = imagecreatetruecolor(60, 30);
// 设置背景颜色为白色
$bgColor = imagecolorallocate($image, 255, 255, 255);
imagefill($image, 0, 0, $bgColor);
// 设置文本颜色为黑色
$textColor = imagecolorallocate($image, 0, 0, 0);
// 在画布上绘制验证码
imagestring($image, 5, 10, 8, $code, $textColor);
// 输出图像
header('Content-Type: image/png');
imagepng($image);
// 释放资源
imagedestroy($image);
?>
```
代码中使用 `session_start()` 函数开启会话,将生成的验证码保存到 `$_SESSION` 中,并且使用 `imagecreatetruecolor()` 函数创建一个宽度为 60 像素、高度为 30 像素的画布。使用 `imagefill()` 函数填充画布背景色,使用 `imagestring()` 函数在画布上绘制验证码文本。最后使用 `header()` 函数设置输出类型,使用 `imagepng()` 函数输出 PNG 格式的图像,并且使用 `imagedestroy()` 函数释放资源。
该示例中生成的验证码比较简单,可以根据需要进行修改。
PHP 画心形
以下是用 PHP 画心形的代码:
```php
<?php
header('Content-Type: image/png');
$width = 300;
$height = 300;
$im = imagecreatetruecolor($width, $height);
$bg = imagecolorallocate($im, 255, 255, 255);
$red = imagecolorallocate($im, 255, 0, 0);
imagefill($im, 0, 0, $bg);
$points = array();
for ($t = 0; $t < 2 * M_PI; $t += 0.01) {
$x = 16 * pow(sin($t), 3);
$y = 13 * cos($t) - 5 * cos(2 * $t) - 2 * cos(3 * $t) - cos(4 * $t);
$points[] = $width / 2 + $x * 10;
$points[] = $height / 2 - $y * 10;
}
imagefilledpolygon($im, $points, count($points) / 2, $red);
imagepng($im);
imagedestroy($im);
```
这段代码使用 PHP 的 GD 库来生成心形图案,并输出为 PNG 格式的图片。首先创建一个 300x300 的画布,并用白色填充。然后,使用 `for` 循环计算心形函数的横纵坐标,并将其加入一个点集中。最后,使用 `imagefilledpolygon` 函数将点集连接成一个心形图案,并填充为红色。执行代码后,会在浏览器中显示生成的心形图案。