蓝色天空.知识 · 实践 · 创造
我的收藏
PHP 教程目录 95章
课程介绍
PHP / LEARN BY DOING

PHP 图像处理

梳理 PHP GD 图像处理扩展启用方式、gd_info() 能力查询与 21 个核心函数,并在 PHP 8.4 CLI 实测真彩画布绘制、PNG 魔数校验、像素读取、元数据解析与仿射缩放。

学完这一章,你能够

  • 梳理 PHP GD 图像处理扩展启用方式、gd_info() 能力查询与 21 个核心函数,并在 PHP 8.4 CLI 实测真彩画布绘制、PNG 魔数校验、像素读取、元数据解析与仿射缩放。

PHP 图像处理与 GD 扩展配置

PHP 通过内置 GD 图像处理扩展支持动态创建画布、绘制图形文字、读写像素、缩放裁剪、仿射变换以及输出 PNG/JPEG/GIF/WebP 等常见栅格图像格式,下表整理了常用的图像信息查询、颜色管理、绘图与矩阵变换函数。

调用 GD 图像处理函数前需确认 `php.ini` 已启用 GD 扩展:历史版本中 Windows 常写作 `extension=php_gd2.dll`、Linux/macOS 常写作 `extension=php_gd2.so`,现代 PHP 8.x 统一简化为 `extension=gd`。

启用后可调用 `gd_info()` 检查编译期支持的图像编解码器与字体引擎。本站使用本地 PHP 8.4.27 CLI(加载 `extension=gd`)实测确认:`GD Version` 为 `'bundled (2.1.0 compatible)'`,`PNG Support`、`JPEG Support`、`GIF Create Support`、`FreeType Support` 与 `WebP Support` 均为 `true`;通过 `imagecreatetruecolor(160, 90)` 配合 `imagecolorallocate()`、`imagefilledrectangle()`、`imagearc()` 与 `imagechar()` 绘制画布并经 `ob_start()` + `imagepng()` 导出后,测得 `imagesx() === 160`、`imagesy() === 90`、前 8 字节 PNG 文件头精确为十六进制 `89504e470d0a1a0a`(`\x89PNG\r\n\x1a\n`);`imagecolorat($img, 25, 25)` 还原 RGB 为 `[30, 120, 210]`,`getimagesizefromstring()` 读回 `160×90` 与 `image/png`;`imageaffinematrixget()`/`imageaffinematrixconcat()`/`imageaffine()` 执行 0.5 倍缩放后输出 `79×45` 图像。

PHP GD 常用图像处理函数参考表

函数功能说明
gd_info()返回当前已加载 GD 扩展的版本号及各图像格式/字体支持状态数组。
getimagesize()读取本地图像文件的像素尺寸、图像类型常量与 MIME 字符串(无需加载整图)。
getimagesizefromstring()直接从内存图像字节串解析宽高、类型常量与 MIME 类型。
image_type_to_extension()根据 IMAGETYPE_* 常量返回对应标准文件扩展名(如 .png)。
image_type_to_mime_type()根据 IMAGETYPE_* 常量返回对应的标准 MIME 类型(如 image/png)。
image2wbmp()将图像转换为黑白 WBMP 格式输出(现代 Web 场景多改用 PNG/WebP)。
imageaffine()按 6 元素 2D 仿射变换矩阵对图像执行平移、缩放、旋转或错切并返回新图像。
imageaffinematrixconcat()将两个 2D 仿射变换矩阵按顺序相乘合并为单个复合矩阵。
imageaffinematrixget()依据变换类型(如 IMG_AFFINE_SCALE、IMG_AFFINE_TRANSLATE)生成仿射矩阵。
imagealphablending()设置真彩图像的 Alpha 混色模式(开启时半透明绘制与底色混合,关闭时直接覆写像素)。
imageantialias()开启或关闭直线与多边形的快速抗锯齿绘制(仅支持真彩图像)。
imagearc()以指定圆心、宽高与起止角度在画布上绘制椭圆弧或完整圆。
imagechar()使用 GD 内置点阵字体在指定坐标水平绘制单个字符。
imagecharup()使用 GD 内置点阵字体在指定坐标自下而上垂直绘制单个字符。
imagecolorallocate()为画布分配由 RGB 分量(0–255)组成的颜色索引值。
imagecolorallocatealpha()为画布分配含 Alpha 透明度(0 不透明至 127 全透明)的颜色值。
imagecolorat()读取指定 (x, y) 像素坐标处的颜色索引或真彩 32 位 ARGB 整数。
imagecolorclosest()在调色板中查找与指定 RGB 值欧氏距离最接近的已分配颜色索引。
imagecolorclosestalpha()查找与指定 RGBA 颜色与透明度最接近的颜色索引。
imagecolorclosesthwb()按色度、白度与黑度空间查找与指定颜色最接近的调色板索引。
imagesx() / imagesy()分别返回 GdImage 对象的当前像素宽度与高度。

在 PHP 8.4 CLI 实测 GD 能力检测、PNG 绘图字节魔数、像素读取与仿射变换

含完整源码 · 121 行
展开查看收起
php
<?php
declare(strict_types=1);

$cases = [];

// Case 1: gd_info() capability report
$info = gd_info();
$infoActual = [
    'gd_loaded' => extension_loaded('gd'),
    'gd_version' => $info['GD Version'],
    'png_support' => $info['PNG Support'],
    'jpeg_support' => $info['JPEG Support'],
    'gif_create_support' => $info['GIF Create Support'],
    'freetype_support' => $info['FreeType Support'],
    'webp_support' => $info['WebP Support'],
];
$infoExpected = [
    'gd_loaded' => true,
    'gd_version' => 'bundled (2.1.0 compatible)',
    'png_support' => true,
    'jpeg_support' => true,
    'gif_create_support' => true,
    'freetype_support' => true,
    'webp_support' => true,
];
$cases[] = [
    'name' => 'gd_info_capabilities',
    'passed' => $infoActual === $infoExpected,
    'expected' => $infoExpected,
    'actual' => $infoActual,
];

// Case 2: imagecreatetruecolor + imagecolorallocate + imagefilledrectangle + imagearc + imagepng magic bytes
$img = imagecreatetruecolor(160, 90);
imagealphablending($img, true);
$bg = imagecolorallocate($img, 240, 248, 255);
$rectColor = imagecolorallocate($img, 30, 120, 210);
$arcColor = imagecolorallocatealpha($img, 220, 60, 40, 32);
imagefilledrectangle($img, 0, 0, 159, 89, $bg);
imagefilledrectangle($img, 10, 10, 80, 60, $rectColor);
imagearc($img, 120, 45, 40, 40, 0, 360, $arcColor);
imagechar($img, 3, 15, 68, 'G', $rectColor);

ob_start();
imagepng($img);
$pngBytes = ob_get_clean();

$drawActual = [
    'width' => imagesx($img),
    'height' => imagesy($img),
    'png_signature_hex' => bin2hex(substr($pngBytes, 0, 8)),
    'png_non_empty' => strlen($pngBytes) > 100,
];
$drawExpected = [
    'width' => 160,
    'height' => 90,
    'png_signature_hex' => '89504e470d0a1a0a',
    'png_non_empty' => true,
];
$cases[] = [
    'name' => 'gd_create_draw_and_png_bytes',
    'passed' => $drawActual === $drawExpected,
    'expected' => $drawExpected,
    'actual' => $drawActual,
];

// Case 3: imagecolorat, getimagesizefromstring, image_type_to_extension, image_type_to_mime_type
$pixel = imagecolorat($img, 25, 25);
$r = ($pixel >> 16) & 0xFF;
$g = ($pixel >> 8) & 0xFF;
$b = $pixel & 0xFF;
$sizeInfo = getimagesizefromstring($pngBytes);

$metaActual = [
    'pixel_rgb' => [$r, $g, $b],
    'parsed_width' => $sizeInfo[0],
    'parsed_height' => $sizeInfo[1],
    'parsed_mime' => $sizeInfo['mime'],
    'type_extension' => image_type_to_extension(IMAGETYPE_PNG),
    'type_mime' => image_type_to_mime_type(IMAGETYPE_PNG),
];
$metaExpected = [
    'pixel_rgb' => [30, 120, 210],
    'parsed_width' => 160,
    'parsed_height' => 90,
    'parsed_mime' => 'image/png',
    'type_extension' => '.png',
    'type_mime' => 'image/png',
];
$cases[] = [
    'name' => 'gd_inspect_pixel_and_metadata',
    'passed' => $metaActual === $metaExpected,
    'expected' => $metaExpected,
    'actual' => $metaActual,
];

// Case 4: imageaffinematrixget / imageaffinematrixconcat / imageaffine
$scaleA = imageaffinematrixget(IMG_AFFINE_SCALE, ['x' => 0.5, 'y' => 0.5]);
$identity = imageaffinematrixget(IMG_AFFINE_TRANSLATE, ['x' => 0, 'y' => 0]);
$combined = imageaffinematrixconcat($scaleA, $identity);
$scaled = imageaffine($img, $combined);

$affineActual = [
    'matrix_len' => count($combined),
    'scaled_width' => imagesx($scaled),
    'scaled_height' => imagesy($scaled),
];
$affineExpected = [
    'matrix_len' => 6,
    'scaled_width' => 79,
    'scaled_height' => 45,
];
$cases[] = [
    'name' => 'gd_affine_transform',
    'passed' => $affineActual === $affineExpected,
    'expected' => $affineExpected,
    'actual' => $affineActual,
];

echo json_encode(['version' => PHP_VERSION, 'cases' => $cases], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . "\n";
核对 GD bundled (2.1.0 compatible) 与 PNG/JPEG/FreeType/WebP 支持、160×90 PNG 魔数 89504e470d0a1a0a、像素 RGB [30, 120, 210]、MIME image/png 及 0.5 倍仿射缩放尺寸 79×45。

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载本章实验包 (mbskycom202612a1232.zip) ↓ 查看运行说明 ↗

本章附件与实例包

下载课程关联工程包:PHP

课程关联工程包(登记关联95章) · 含当前章节或实例 · mbskycom202612a1232.zip

下载课程关联工程包:PHP

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1255.zip

常见错误与边界检查

  • 实际端口、文档资源与应用配置都应和测试条件一致。

技术规范与官方资料

练习与参考解答

查看参考解答

PHP 8 起 GD 句柄已从 resource 升级为 GdImage 对象,离开作用域后由垃圾回收自动释放(imagedestroy() 变为空操作);向浏览器输出 PNG 前不能有任何前置空白或 BOM 文本输出,且需发送 Content-Type: image/png 响应头。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习