如何用PHP为叠加文字的图片添加下载分享按钮 导出固定宽高JPG
原生PHP实现带文字叠加图片的下载/分享功能
核心实现逻辑
所有图片合成、导出操作完全在服务端通过PHP原生GD库完成,无需调用任何前端截图工具,完全符合要求:
- 预先定义导出图片的固定宽高参数,合成时严格按照该尺寸输出
- 下载按钮直接请求后端生成接口,返回头设置为附件格式触发浏览器下载
- 分享功能可将生成的图片暂存到服务端临时目录,返回可访问地址供前端使用
前置依赖检查
先确认PHP环境已开启GD库,可通过以下代码验证:
<?php var_dump(extension_loaded('gd'));
若返回bool(true)则可正常使用。
完整实现代码
1. 公共图片合成函数(image_generate.php)
<?php /** * 生成固定宽高、叠加指定文字的JPG图片 * @param int $width 固定输出宽度 * @param int $height 固定输出高度 * @param string $text 要叠加的文字 * @param string $fontPath 字体文件路径 * @return resource|bool 生成的GD图像资源,失败返回false */ function generateTextImage($width = 800, $height = 600, $text = '默认叠加文字', $fontPath = './simhei.ttf') { // 创建空白画布 $image = imagecreatetruecolor($width, $height); // 填充背景色(可替换为读取已有底图的逻辑) $bgColor = imagecolorallocate($image, 255, 255, 255); imagefill($image, 0, 0, $bgColor); // 如果需要用已有图片作为底图,替换上面的空白画布逻辑为: // $sourceImage = imagecreatefromjpeg('./base_image.jpg'); // imagecopyresampled($image, $sourceImage, 0, 0, 0, 0, $width, $height, imagesx($sourceImage), imagesy($sourceImage)); // imagedestroy($sourceImage); // 设置文字颜色 $textColor = imagecolorallocate($image, 0, 0, 0); // 计算文字居中位置 $fontSize = 24; $textBox = imagettfbbox($fontSize, 0, $fontPath, $text); $textX = ($width - ($textBox[2] - $textBox[0])) / 2; $textY = ($height - ($textBox[1] - $textBox[7])) / 2; // 写入文字 imagettftext($image, $fontSize, 0, $textX, $textY, $textColor, $fontPath, $text); return $image; }
注:需提前准备字体文件放到对应路径,避免中文乱码问题
2. 图片下载接口(download.php)
<?php require_once './image_generate.php'; // 定义固定导出尺寸 define('EXPORT_WIDTH', 800); define('EXPORT_HEIGHT', 600); // 获取前端传递的叠加文字(可根据业务调整参数) $text = isset($_GET['text']) ? htmlspecialchars_decode($_GET['text']) : '默认文字'; // 生成图片 $image = generateTextImage(EXPORT_WIDTH, EXPORT_HEIGHT, $text); if (!$image) { die('图片生成失败'); } // 设置下载头 header('Content-Type: image/jpeg'); header('Content-Disposition: attachment; filename="generated_image.jpg"'); // 输出JPG,质量参数可调整(0-100) imagejpeg($image, null, 90); // 销毁资源 imagedestroy($image); exit;
3. 图片分享接口(share.php)
<?php require_once './image_generate.php'; define('EXPORT_WIDTH', 800); define('EXPORT_HEIGHT', 600); // 临时文件存储目录,需保证有写入权限 $tempDir = './temp_share/'; if (!is_dir($tempDir)) { mkdir($tempDir, 0755, true); } $text = isset($_GET['text']) ? htmlspecialchars_decode($_GET['text']) : '默认文字'; $image = generateTextImage(EXPORT_WIDTH, EXPORT_HEIGHT, $text); if (!$image) { die(json_encode(['code' => 1, 'msg' => '生成失败'])); } // 生成唯一文件名 $fileName = uniqid() . '.jpg'; $savePath = $tempDir . $fileName; imagejpeg($image, $savePath, 90); imagedestroy($image); // 拼接可访问的分享地址(根据实际域名调整) $shareUrl = 'https://your-domain.com/temp_share/' . $fileName; echo json_encode(['code' => 0, 'share_url' => $shareUrl]); exit;
4. 前端页面示例
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>图片下载分享</title> </head> <body> <input type="text" id="customText" placeholder="输入要叠加的文字" value="测试叠加文字"> <!-- 下载按钮 --> <a href="javascript:;" id="downloadBtn">下载图片</a> <!-- 分享按钮 --> <button id="shareBtn">生成分享地址</button> <p id="shareUrlBox"></p> <script> const downloadBtn = document.getElementById('downloadBtn'); const shareBtn = document.getElementById('shareBtn'); const customText = document.getElementById('customText'); // 下载逻辑 downloadBtn.onclick = function() { const text = encodeURIComponent(customText.value); window.open(`./download.php?text=${text}`); } // 分享逻辑 shareBtn.onclick = function() { const text = encodeURIComponent(customText.value); fetch(`./share.php?text=${text}`) .then(res => res.json()) .then(data => { if (data.code === 0) { document.getElementById('shareUrlBox').innerText = `分享地址:${data.share_url}`; } }) } </script> </body> </html>
注意事项
- 临时分享目录可配置定时任务清理超过24小时的图片,避免占用服务器存储
- 字体文件建议选择支持中文的字体,避免文字显示异常
- 若底图是PNG格式,可将
imagecreatefromjpeg替换为imagecreatefrompng,输出格式仍可导出为JPG
内容的提问来源于stack exchange,提问作者Mr. Naresh Chauhan
相关产品推荐
相关产品推荐

