本文目录导读:

在PHP项目中实现文生图,主要有以下几种路径,你可以根据项目需求和预算选择:
调用云端API(最推荐、最简单)
这是目前最主流的方式,PHP作为客户端发送请求即可。
OpenAI DALL-E 3
<?php
$apiKey = '你的API_KEY';
$prompt = '一只戴着礼帽的猫,油画风格';
$ch = curl_init('https://api.openai.com/v1/images/generations');
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_HTTPHEADER => [
'Content-Type: application/json',
'Authorization: Bearer ' . $apiKey
],
CURLOPT_POSTFIELDS => json_encode([
'model' => 'dall-e-3',
'prompt' => $prompt,
'n' => 1,
'size' => '1024x1024'
]),
CURLOPT_RETURNTRANSFER => true
]);
$response = curl_exec($ch);
curl_close($ch);
$data = json_decode($response, true);
$imageUrl = $data['data'][0]['url'] ?? null;
// 下载图片到本地
if ($imageUrl) {
file_put_contents('generated_image.png', file_get_contents($imageUrl));
}
?>
其他云API
- Stable Diffusion API(Stability AI、Replicate)
- 通义万相(阿里云)
- 百度文心一格
- 腾讯混元
优缺点
✅ 简单、快速、质量高
❌ 需要付费、依赖网络、有限速
本地部署开源模型
适合对数据安全要求高、或需要大量生成不依赖外部服务的场景。
使用 PHP 调用 Python 脚本
<?php
$prompt = escapeshellarg('a cute cat, digital art');
$command = "python3 /path/to/generate.py --prompt $prompt --output output.png";
$output = shell_exec($command);
if (file_exists('output.png')) {
echo '图片已生成';
}
?>
Python 脚本示例(使用Stable Diffusion)
# generate.py
import sys
import argparse
from diffusers import StableDiffusionPipeline
import torch
parser = argparse.ArgumentParser()
parser.add_argument('--prompt', required=True)
parser.add_argument('--output', default='output.png')
args = parser.parse_args()
pipe = StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5")
pipe = pipe.to("cuda") # 有GPU
image = pipe(args.prompt).images[0]
image.save(args.output)
使用 PHP 的 ImageMagick(简单合成,非AI)
<?php // 基于模板合成文字生成简单图片 $image = imagecreate(800, 400); $bg = imagecolorallocate($image, 255, 255, 255); $textColor = imagecolorallocate($image, 0, 0, 0); imagestring($image, 5, 50, 150, "你输入的文本内容", $textColor); imagepng($image, 'text_image.png'); imagedestroy($image); ?>
使用PHP插画/图形库
GD库(PHP内置)
<?php
header('Content-Type: image/png');
$image = imagecreatetruecolor(400, 300);
// 设置颜色
$blue = imagecolorallocate($image, 0, 102, 204);
$white = imagecolorallocate($image, 255, 255, 255);
// 绘制背景和文字
imagefill($image, 0, 0, $blue);
imagettftext($image, 20, 0, 50, 150, $white, './font.ttf', 'Hello World!');
imagepng($image);
imagedestroy($image);
?>
Imagine库(更高级的抽象)
composer require imagine/imagine
<?php
use Imagine\Gd\Imagine;
use Imagine\Image\Box;
use Imagine\Image\Point;
$imagine = new Imagine();
$image = $imagine->create(new Box(800, 600));
// 绘制文字
$image->draw()->text(
'Your Text Here',
new Imagine\Image\Font('/path/to/font.ttf', 30, $image->palette()->color('#ffffff')),
new Point(100, 200)
);
$image->save('output.jpg');
?>
项目架构建议
用户输入文本
↓
PHP后端处理
↓
├── 云端API路线:cURL → AI服务 → 返回URL/图片
├── 本地模型路线:exec Python脚本 → 本地生成
└── 简单图形路线:GD/Imagine库 → 生成合成图
↓
返回/保存图片
选择建议
| 场景 | 推荐方案 |
|---|---|
| 快速原型、商业项目 | OpenAI/Stability API |
| 私有化部署 | Stable Diffusion + Python |
| 简单文字合成 | GD/Imagine库 |
| 高并发、低延迟 | 云API + 缓存 |
注意事项
- 性能优化:图片生成通常较慢(3-30秒),建议使用异步队列(如Redis+Worker)
- 成本控制:缓存生成结果,避免重复生成相同内容审核**:对用户输入进行安全过滤,避免生成违规内容
- 错误处理:API调用可能失败,需做好重试和降级
最常见的生产方案是:PHP作为API网关,调用专业的AI绘画服务(云端或本地),而不是直接让PHP进行复杂的图像生成计算。