PHP图片处理|画布入门

以下是基于 PHP7.4 的 GD 库实现图片文字写入、绘制图案、渲染已有图片、设置背景色的完整代码案例兼容 PHP7.4 及以上版本:

前置说明

  1. 确保服务器已安装 GD 扩展:php -m | grep gd 查看是否存在
  2. GD 库常用函数在 PHP7.4 中均兼容,无需特殊适配

案例1:设置画布背景色 + 写入文字

php 复制代码
<?php
/**
 * 案例1:创建画布并设置背景色,写入自定义文字
 * 功能:创建指定尺寸画布 → 设置背景色 → 写入带样式的文字 → 输出/保存图片
 */
// 1. 定义画布尺寸
$width = 500;  // 画布宽度
$height = 200; // 画布高度

// 2. 创建画布资源(true color 真彩色画布,避免颜色失真)
$canvas = imagecreatetruecolor($width, $height);
if (!$canvas) {
    die("创建画布失败,请检查GD扩展是否安装");
}

// 3. 定义颜色(imagecolorallocate:为画布分配颜色,参数:画布资源,R, G, B)
$bgColor = imagecolorallocate($canvas, 240, 248, 255); // 背景色:淡蓝色
$textColor = imagecolorallocate($canvas, 220, 20, 60); // 文字色:深红色
$borderColor = imagecolorallocate($canvas, 100, 149, 237); // 边框色:玉米蓝

// 4. 设置画布背景色(填充整个画布)
imagefill($canvas, 0, 0, $bgColor);

// 5. 绘制文字(需确保服务器有对应字体文件,此处以系统宋体为例,可替换为绝对路径)
$text = "PHP7.4 图片文字写入示例"; // 要写入的文字
$fontSize = 20; // 字体大小(像素)
$fontFile = "simsun.ttf"; // 字体文件(需确保路径存在,Windows:C:/Windows/Fonts/simsun.ttc,Linux:/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf)

// 处理字体文件不存在的情况
if (!file_exists($fontFile)) {
    // 降级使用内置字体(效果较差,仅兼容英文字符,中文会乱码)
    imagestring($canvas, 5, 50, 80, "PHP7.4 Text Demo (No Font File)", $textColor);
} else {
    // 使用 imagettftext 绘制带字体的文字(支持中文)
    // 参数:画布、字体大小、旋转角度、X坐标、Y坐标、颜色、字体文件、文字内容
    imagettftext($canvas, $fontSize, 0, 50, 100, $textColor, $fontFile, $text);
}

// 6. 绘制边框(可选)
imagerectangle($canvas, 1, 1, $width-2, $height-2, $borderColor);

// 7. 输出图片到浏览器(设置响应头,确保正确渲染)
header("Content-Type: image/png");
imagepng($canvas); // 输出PNG格式(也可使用imagejpeg/jpg,需调整质量)

// 8. 保存图片到服务器(可选)
// imagepng($canvas, "./text_image.png");

// 9. 销毁画布资源(释放内存)
imagedestroy($canvas);
?>

案例2:绘制基础图案(矩形、圆形、线条、多边形)

php 复制代码
<?php
/**
 * 案例2:在画布上绘制各类基础图案
 * 功能:创建画布 → 设置背景 → 绘制矩形/圆形/线条/多边形 → 输出图片
 */
// 1. 创建画布
$width = 600;
$height = 400;
$canvas = imagecreatetruecolor($width, $height);

// 2. 定义颜色
$bgColor = imagecolorallocate($canvas, 255, 255, 255); // 白色背景
$red = imagecolorallocate($canvas, 255, 0, 0); // 红色
$green = imagecolorallocate($canvas, 0, 255, 0); // 绿色
$blue = imagecolorallocate($canvas, 0, 0, 255); // 蓝色
$yellow = imagecolorallocate($canvas, 255, 255, 0); // 黄色

// 3. 填充背景
imagefill($canvas, 0, 0, $bgColor);

// 4. 绘制图案
// 4.1 绘制矩形(空心):imagerectangle(画布, 左上角X, 左上角Y, 右下角X, 右下角Y, 颜色)
imagerectangle($canvas, 50, 50, 150, 150, $red);

// 4.2 绘制填充矩形:imagefilledrectangle(参数同imagerectangle)
imagefilledrectangle($canvas, 200, 50, 300, 150, $green);

// 4.3 绘制圆形(椭圆):imageellipse(画布, 圆心X, 圆心Y, 宽, 高, 颜色)
imageellipse($canvas, 400, 100, 100, 100, $blue); // 宽高相等即为圆形

// 4.4 绘制填充圆形:imagefilledellipse(参数同imageellipse)
imagefilledellipse($canvas, 500, 100, 80, 80, $yellow);

// 4.5 绘制线条:imageline(画布, 起点X, 起点Y, 终点X, 终点Y, 颜色)
imageline($canvas, 50, 200, 550, 200, $red); // 水平线
imageline($canvas, 300, 200, 300, 350, $green); // 垂直线

// 4.6 绘制多边形:imagepolygon(画布, 坐标数组, 顶点数, 颜色)
$polyPoints = [
    100, 300, // 顶点1
    150, 250, // 顶点2
    200, 300, // 顶点3
    180, 350, // 顶点4
    120, 350  // 顶点5
];
imagepolygon($canvas, $polyPoints, 5, $blue);

// 4.7 绘制填充多边形:imagefilledpolygon
$polyPoints2 = [
    300, 250,
    350, 220,
    400, 250,
    380, 300,
    320, 300
];
imagefilledpolygon($canvas, $polyPoints2, 5, $yellow);

// 5. 输出图片
header("Content-Type: image/png");
imagepng($canvas);

// 6. 释放资源
imagedestroy($canvas);
?>

案例3:将已有图片渲染到画布(图片合成)

php 复制代码
<?php
/**
 * 案例3:加载已有图片并渲染到新画布(支持JPG/PNG/GIF)
 * 功能:创建画布 → 加载源图片 → 缩放/平铺渲染到画布 → 输出合成图
 */
// 1. 定义画布尺寸
$canvasWidth = 800;
$canvasHeight = 600;

// 2. 源图片路径(替换为你的图片路径)
$sourceImagePath = "./source_image.png"; // 支持jpg/png/gif
if (!file_exists($sourceImagePath)) {
    die("源图片不存在:{$sourceImagePath}");
}

// 3. 创建目标画布
$canvas = imagecreatetruecolor($canvasWidth, $canvasHeight);

// 4. 设置画布背景色(白色)
$bgColor = imagecolorallocate($canvas, 255, 255, 255);
imagefill($canvas, 0, 0, $bgColor);

// 5. 加载源图片(自动识别格式)
function loadImage($path) {
    $info = getimagesize($path);
    $type = image_type_to_extension($info[2], false); // 获取图片类型(jpg/png/gif)
    $loadFunc = "imagecreatefrom{$type}"; // 拼接加载函数名
    if (!function_exists($loadFunc)) {
        die("不支持的图片格式:{$type}");
    }
    return $loadFunc($path);
}
$sourceImage = loadImage($sourceImagePath);

// 6. 获取源图片尺寸
$sourceWidth = imagesx($sourceImage);
$sourceHeight = imagesy($sourceImage);

// 7. 渲染源图片到画布(三种方式可选)

// 方式1:原尺寸渲染(坐标X=100, Y=100)
// imagecopy(目标画布, 源图片, 目标X, 目标Y, 源X, 源Y, 源宽度, 源高度)
// imagecopy($canvas, $sourceImage, 100, 100, 0, 0, $sourceWidth, $sourceHeight);

// 方式2:缩放渲染(缩放到200x200)
$targetWidth = 200;
$targetHeight = 200;
// imagecopyresampled(目标画布, 源图片, 目标X, 目标Y, 源X, 源Y, 目标宽度, 目标高度, 源宽度, 源高度)
imagecopyresampled(
    $canvas, $sourceImage,
    100, 100, 0, 0,
    $targetWidth, $targetHeight,
    $sourceWidth, $sourceHeight
);

// 方式3:平铺渲染(铺满整个画布)
/*
for ($x = 0; $x < $canvasWidth; $x += $sourceWidth) {
    for ($y = 0; $y < $canvasHeight; $y += $sourceHeight) {
        imagecopy($canvas, $sourceImage, $x, $y, 0, 0, $sourceWidth, $sourceHeight);
    }
}
*/

// 8. 可选:在合成图上添加文字标注
$textColor = imagecolorallocate($canvas, 255, 0, 0);
$fontFile = "simsun.ttf";
if (file_exists($fontFile)) {
    imagettftext($canvas, 16, 0, 100, 320, $textColor, $fontFile, "合成后的图片示例");
}

// 9. 输出图片
header("Content-Type: image/png");
imagepng($canvas);

// 10. 释放资源
imagedestroy($sourceImage);
imagedestroy($canvas);
?>

关键注意事项

  1. 字体文件路径

    • Windows:宋体路径 C:/Windows/Fonts/simsun.ttc
    • Linux:需安装中文字体,如 DejaVuSans.ttf(路径 /usr/share/fonts/truetype/dejavu/DejaVuSans.ttf
    • 中文乱码问题:必须使用 imagettftext + 中文字体文件,imagestring 仅支持ASCII字符
  2. 图片格式兼容

    • imagepng():输出PNG(无损,支持透明)
    • imagejpeg():输出JPG(可设置质量,imagejpeg($canvas, null, 90) 90为质量)
    • imagegif():输出GIF(支持动图,但GD对动图处理有限)
  3. 内存管理

    • 每次创建画布/加载图片后,必须用 imagedestroy() 释放资源,避免内存泄漏
    • 处理大图片时,可通过 ini_set('memory_limit', '256M') 提升内存限制
  4. 错误处理

    • 使用 file_exists() 检查文件是否存在
    • 使用 getimagesize() 验证图片有效性
    • 捕获 GD 函数返回的 false,避免脚本崩溃

以上案例可直接运行(替换字体/图片路径),覆盖了PHP7.4中图片处理的核心场景,如需调整样式(如文字旋转、透明度、滤镜等),可基于基础函数扩展。

相关推荐
BingoGo2 天前
当你的 PHP 应用的 API 没有限流时会发生什么?
后端·php
JaguarJack2 天前
当你的 PHP 应用的 API 没有限流时会发生什么?
后端·php·服务端
BingoGo3 天前
OpenSwoole 26.2.0 发布:支持 PHP 8.5、io_uring 后端及协程调试改进
后端·php
JaguarJack3 天前
OpenSwoole 26.2.0 发布:支持 PHP 8.5、io_uring 后端及协程调试改进
后端·php·服务端
JaguarJack4 天前
推荐 PHP 属性(Attributes) 简洁读取 API 扩展包
后端·php·服务端
BingoGo4 天前
推荐 PHP 属性(Attributes) 简洁读取 API 扩展包
php
JaguarJack5 天前
告别 Laravel 缓慢的 Blade!Livewire Blaze 来了,为你的 Laravel 性能提速
后端·php·laravel
郑州光合科技余经理5 天前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
feifeigo1235 天前
matlab画图工具
开发语言·matlab
dustcell.5 天前
haproxy七层代理
java·开发语言·前端