引言
准备工作
在开始之前,请确保你的服务器已安装PHP和GD库。GD库是PHP的一个图像处理库,支持多种图像格式。
1. 创建图片资源
// 创建一个空白图像,指定宽度和高度
$image = imagecreatetruecolor(100, 50);
// 设置背景颜色
$white = imagecolorallocate($image, 255, 255, 255);
imagefill($image, 0, 0, $white);
2. 绘制图形
在图像资源上绘制各种图形,如矩形、圆形、线条等。以下是一些常用的绘图函数:
// 绘制矩形
$red = imagecolorallocate($image, 255, 0, 0);
imagerectangle($image, 10, 10, 90, 40, $red);
// 绘制圆形
$blue = imagecolorallocate($image, 0, 0, 255);
imagefilledellipse($image, 50, 25, 40, 40, $blue);
// 绘制线条
$green = imagecolorallocate($image, 0, 255, 0);
imageline($image, 10, 10, 90, 40, $green);
3. 添加文字
在图像上添加文字,可以使用以下函数:
// 设置字体路径
$font_path = 'arial.ttf';
// 加载字体
$font = imagettfbbox(20, 0, $font_path, 'Hello, World!');
// 计算文字位置
$x = (100 - $font[4]) / 2;
$y = (50 - ($font[5] + $font[7])) / 2;
// 添加文字
$black = imagecolorallocate($image, 0, 0, 0);
imagettftext($image, 20, 0, $x, $y, $black, $font_path, 'Hello, World!');
4. 保存图片
将图像保存到服务器上的指定路径:
// 设置图片格式
imagejpeg($image, 'image.jpg');
// 释放图像资源
imagedestroy($image);
5. 输出图片
header('Content-Type: image/jpeg');
imagejpeg($image);
imagedestroy($image);