当前位置: 首页> 最新文章列表> imagecreatetruecolor() + imageopenpolygon():从零开始创建图像

imagecreatetruecolor() + imageopenpolygon():从零开始创建图像

M66 2025-05-29

在 PHP 中,图像处理功能由 GD 库提供,imagecreatetruecolor()imageopenpolygon() 是其中非常有用的两个函数。本文将为您展示如何使用这两个函数从零开始创建图像并绘制一个简单的多边形。我们将一步步介绍如何创建图像,设置图像颜色,并使用多边形方法将图形呈现出来。

1. 使用 imagecreatetruecolor() 创建图像

imagecreatetruecolor() 是一个非常基础的函数,用于创建一个真彩色图像资源。它接收两个参数:图像的宽度和高度,返回一个表示图像的资源。

<?php
// 创建一个宽 500 高 500 的图像
$width = 500;
$height = 500;
$image = imagecreatetruecolor($width, $height);

这个函数返回的 $image 变量就是图像的资源,接下来你可以用它来进行图像处理操作。

2. 分配颜色

在图像中,我们通常需要设置不同的颜色来绘制形状、背景等。可以使用 imagecolorallocate() 来分配颜色。它接受 4 个参数:图像资源、红色、绿色和蓝色的值(0-255)。

// 分配背景色和多边形颜色
$background_color = imagecolorallocate($image, 255, 255, 255);  // 白色背景
$polygon_color = imagecolorallocate($image, 0, 0, 255);        // 蓝色多边形

3. 填充背景色

使用 imagefill() 可以将整个图像填充为指定的颜色。例如,在我们创建图像后,我们要填充一个白色背景。

// 填充背景色
imagefill($image, 0, 0, $background_color);

4. 使用 imagepolygon() 绘制多边形

接下来,我们使用 imagepolygon() 绘制一个多边形。该函数的参数包括图像资源、顶点坐标数组和顶点数。多边形的每个顶点由一个坐标(x, y)来表示。

// 多边形的顶点坐标
$points = array(
    150, 150,
    350, 150,
    400, 350,
    200, 400,
    100, 300
);

// 绘制多边形
imagepolygon($image, $points, 5, $polygon_color);

5. 输出图像

最后,我们需要输出创建的图像。PHP 提供了 imagepng()imagejpeg()imagegif() 等函数,您可以根据需要选择其中一种来输出图像。在此,我们使用 imagepng() 将图像保存为 PNG 格式。

// 输出图像到浏览器
header('Content-Type: image/png');
imagepng($image);

// 或者保存为文件
// imagepng($image, 'polygon_image.png');

6. 释放资源

一旦图像生成完毕,为了节省内存,应该释放图像资源。

// 销毁图像资源
imagedestroy($image);

完整代码示例

<?php
// 创建图像资源
$width = 500;
$height = 500;
$image = imagecreatetruecolor($width, $height);

// 分配颜色
$background_color = imagecolorallocate($image, 255, 255, 255);  // 白色背景
$polygon_color = imagecolorallocate($image, 0, 0, 255);        // 蓝色多边形

// 填充背景色
imagefill($image, 0, 0, $background_color);

// 多边形的顶点坐标
$points = array(
    150, 150,
    350, 150,
    400, 350,
    200, 400,
    100, 300
);

// 绘制多边形
imagepolygon($image, $points, 5, $polygon_color);

// 输出图像
header('Content-Type: image/png');
imagepng($image);

// 销毁图像资源
imagedestroy($image);
?>