先确认GD库已启用,再通过PHP命令行脚本实现图片缩放、水印添加及批量处理功能。

在PHP中处理图片,通常依赖GD库或ImageMagick扩展。通过命令行运行PHP脚本,可以实现自动化图像处理任务,比如缩放、裁剪、水印添加等。下面介绍如何使用PHP命令行结合GD库完成常见图片操作。
确认GD库已启用
在使用图片处理功能前,确保你的PHP环境已启用GD库:
php -m | grep gd如果输出包含 gd,说明已安装。如果没有,需手动开启:
编辑 php.ini 文件(可通过 php --ini 查看路径)取消注释 extension=gd 这一行保存后重启服务或直接在CLI中测试基本图片缩放操作
创建一个PHP脚本 resize.php,用于将图片按比例缩小:
立即学习“PHP免费学习笔记(深入)”;
<?phpfunction resizeImage($sourcePath, $targetPath, $maxWidth = 800) { // 检查文件是否存在 if (!file_exists($sourcePath)) { die("源图片不存在:$sourcePath\n"); }<pre class='brush:php;toolbar:false;'>// 获取图片信息list($width, $height, $type) = getimagesize($sourcePath);// 计算新尺寸if ($width <= $maxWidth) { copy($sourcePath, $targetPath); echo "图片无需缩放,已复制。\n"; return;}$ratio = $maxWidth / $width;$newWidth = $maxWidth;$newHeight = intval($height * $ratio);// 创建源图像资源switch ($type) { case IMAGETYPE_JPEG: $srcImg = imagecreatefromjpeg($sourcePath); break; case IMAGETYPE_PNG: $srcImg = imagecreatefrompng($sourcePath); break; default: die("不支持的图片格式\n");}// 创建目标图像资源$dstImg = imagecreatetruecolor($newWidth, $newHeight);imagecopyresampled($dstImg, $srcImg, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);// 保存结果imagejpeg($dstImg, $targetPath, 90);imagedestroy($srcImg);imagedestroy($dstImg);echo "图片已缩放并保存至:$targetPath\n";登录后复制}
// 命令行参数处理if ($argc < 3) {echo "用法:php resize.php <源图片> <目标图片> [最大宽度]\n";exit(1);}
$source = $argv[1];$target = $argv[2];$maxWidth = isset($argv[3]) ? (int)$argv[3] : 800;
resizeImage($source, $target, $maxWidth);?>
执行命令进行缩放:
图酷AI 下载即用!可以免费使用的AI图像处理工具,致力于为用户提供最先进的AI图像处理技术,让图像编辑变得简单高效。
22 查看详情
php resize.php photo.jpg thumb.jpg 600添加文字水印
增强版权保护,可在图片右下角添加半透明文字:
// 在原函数基础上扩展水印功能function addWatermark($imagePath, $text = 'Copyright') { $img = imagecreatefromjpeg($imagePath); $color = imagecolorallocatealpha($img, 255, 255, 255, 70); // 半透明白色 $fontFile = '/path/to/arial.ttf'; // 系统字体路径<pre class='brush:php;toolbar:false;'>$fontSize = 20;$bbox = imagettfbbox($fontSize, 0, $fontFile, $text);$textWidth = $bbox[2] - $bbox[0];$textHeight = $bbox[7] - $bbox[1];$x = imagesx($img) - $textWidth - 20;$y = imagesy($img) - $textHeight - 20;imagettftext($img, $fontSize, 0, $x, $y, $color, $fontFile, $text);imagejpeg($img, $imagePath, 90); // 覆盖原图或另存imagedestroy($img);登录后复制}
调用时先缩放再加水印,适合批量处理流程。
命令行批量处理示例
结合Shell脚本对目录内所有JPG图片处理:
#!/bin/bashfor file in *.jpg; do php resize.php "$file" "thumb_$file" 500done登录后复制
赋予执行权限后运行,即可批量生成缩略图。
基本上就这些。只要GD库可用,PHP命令行动态处理图片非常灵活,适合集成到自动化脚本或定时任务中。注意检查路径、权限和内存限制(memory_limit 可在脚本开头调大),避免大图处理时报错。
以上就是PHP命令怎么实现图片处理_PHP命令行图片处理与GD库使用的详细内容,更多请关注php中文网其它相关文章!



