本文目录导读:

我来介绍几种在PHP项目中实现AI绘画的方法,从简单到完整方案逐步说明。
调用第三方AI绘画API(最常用方案)
Stable Diffusion API 示例
<?php
class AIPainting {
private $apiKey;
private $apiUrl;
public function __construct($apiKey, $apiUrl = 'https://api.stability.ai/v1') {
$this->apiKey = $apiKey;
$this->apiUrl = $apiUrl;
}
// 生成图像
public function generateImage($prompt, $options = []) {
$data = [
'text_prompts' => [
['text' => $prompt, 'weight' => 1]
],
'cfg_scale' => $options['cfg_scale'] ?? 7,
'height' => $options['height'] ?? 512,
'width' => $options['width'] ?? 512,
'samples' => $options['samples'] ?? 1,
'steps' => $options['steps'] ?? 50,
];
if (!empty($options['negative_prompt'])) {
$data['text_prompts'][] = [
'text' => $options['negative_prompt'],
'weight' => -1
];
}
$ch = curl_init($this->apiUrl . '/generation/stable-diffusion-v1-6/text-to-image');
curl_setopt_array($ch, [
CURLOPT_HTTPHEADER => [
'Content-Type: application/json',
'Authorization: Bearer ' . $this->apiKey
],
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => json_encode($data),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 60
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode !== 200) {
throw new Exception('API请求失败: ' . $response);
}
return json_decode($response, true);
}
// 保存图像到本地
public function saveImages($result, $saveDir = 'images/') {
if (!is_dir($saveDir)) {
mkdir($saveDir, 0777, true);
}
$savedFiles = [];
foreach ($result['artifacts'] as $index => $artifact) {
$filename = $saveDir . 'ai_' . time() . '_' . $index . '.png';
file_put_contents($filename, base64_decode($artifact['base64']));
$savedFiles[] = $filename;
}
return $savedFiles;
}
}
// 使用示例
$painter = new AIPainting('your-api-key-here');
try {
$result = $painter->generateImage(
'A beautiful sunset over mountains, digital art',
['width' => 1024, 'height' => 1024, 'negative_prompt' => 'blurry, low quality']
);
$files = $painter->saveImages($result);
echo "图像已保存到: " . implode(', ', $files);
} catch (Exception $e) {
echo "错误: " . $e->getMessage();
}
?>
DALL-E 3 API 示例
<?php
class DallePainting {
private $apiKey;
public function __construct($apiKey) {
$this->apiKey = $apiKey;
}
public function generateImage($prompt, $options = []) {
$data = [
'model' => 'dall-e-3',
'prompt' => $prompt,
'n' => $options['n'] ?? 1,
'size' => $options['size'] ?? '1024x1024',
'quality' => $options['quality'] ?? 'standard'
];
$ch = curl_init('https://api.openai.com/v1/images/generations');
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_HTTPHEADER => [
'Content-Type: application/json',
'Authorization: Bearer ' . $this->apiKey
],
CURLOPT_POSTFIELDS => json_encode($data),
CURLOPT_TIMEOUT => 30
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode !== 200) {
throw new Exception('DALL-E API错误: ' . $response);
}
return json_decode($response, true);
}
}
?>
本地Stable Diffusion WebUI方案
部署本地SD WebUI
# 安装依赖 git clone https://github.com/AUTOMATIC1111/stable-diffusion-webui.git cd stable-diffusion-webui # 运行WebUI并开启API python launch.py --api --listen
PHP调用本地SD WebUI API
<?php
class LocalSDPainter {
private $baseUrl;
public function __construct($baseUrl = 'http://127.0.0.1:7860') {
$this->baseUrl = $baseUrl;
}
public function txt2img($payload) {
$defaultPayload = [
'prompt' => '',
'negative_prompt' => '',
'steps' => 20,
'cfg_scale' => 7,
'width' => 512,
'height' => 512,
'sampler_name' => 'Euler a',
'batch_size' => 1,
'n_iter' => 1,
];
$payload = array_merge($defaultPayload, $payload);
$ch = curl_init($this->baseUrl . '/sdapi/v1/txt2img');
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
CURLOPT_POSTFIELDS => json_encode($payload),
CURLOPT_TIMEOUT => 120
]);
$response = curl_exec($ch);
curl_close($ch);
return json_decode($response, true);
}
public function img2img($initImage, $payload) {
$defaultPayload = [
'prompt' => '',
'negative_prompt' => '',
'steps' => 20,
'denoising_strength' => 0.7,
];
$payload = array_merge($defaultPayload, $payload);
$payload['init_images'] = [$initImage];
$ch = curl_init($this->baseUrl . '/sdapi/v1/img2img');
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
CURLOPT_POSTFIELDS => json_encode($payload),
CURLOPT_TIMEOUT => 120
]);
$response = curl_exec($ch);
curl_close($ch);
return json_decode($response, true);
}
}
// 使用示例
$painter = new LocalSDPainter();
// 文生图
$result = $painter->txt2img([
'prompt' => 'a beautiful landscape painting',
'negative_prompt' => 'ugly, blurry',
'width' => 768,
'height' => 512
]);
// 保存生成的图片
foreach ($result['images'] as $index => $image) {
$filename = 'sd_output_' . time() . '_' . $index . '.png';
file_put_contents($filename, base64_decode($image));
}
?>
完整Web应用示例
简单的AI绘画网站
<?php
// ai_painting.php
session_start();
require_once 'AIPainting.php';
$message = '';
$images = [];
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$prompt = $_POST['prompt'] ?? '';
$apiKey = $_POST['api_key'] ?? '';
if (!empty($prompt) && !empty($apiKey)) {
try {
$painter = new AIPainting($apiKey);
$result = $painter->generateImage($prompt, [
'width' => (int)($_POST['width'] ?? 512),
'height' => (int)($_POST['height'] ?? 512),
'negative_prompt' => $_POST['negative_prompt'] ?? ''
]);
$images = $painter->saveImages($result);
$message = '✅ 图像生成成功!';
} catch (Exception $e) {
$message = '❌ 错误: ' . $e->getMessage();
}
} else {
$message = '⚠️ 请填写提示词和API Key';
}
}
?>
<!DOCTYPE html>
<html>
<head>AI绘画工具</title>
<style>
body { font-family: Arial; max-width: 1200px; margin: 0 auto; padding: 20px; }
.container { display: grid; grid-template-columns: 1fr 1fr; gap: 20px; }
.form-group { margin-bottom: 15px; }
label { display: block; margin-bottom: 5px; font-weight: bold; }
input, textarea, select { width: 100%; padding: 8px; }
button { background: #007bff; color: white; border: none; padding: 10px 20px; cursor: pointer; }
.gallery { display: grid; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); gap: 10px; }
.gallery img { width: 100%; height: auto; border-radius: 5px; }
.message { padding: 10px; margin: 10px 0; border-radius: 5px; }
</style>
</head>
<body>
<h1>🎨 AI绘画生成器</h1>
<?php if ($message): ?>
<div class="message"><?= $message ?></div>
<?php endif; ?>
<div class="container">
<div>
<form method="POST">
<div class="form-group">
<label>API Key</label>
<input type="password" name="api_key" required placeholder="输入你的API Key">
</div>
<div class="form-group">
<label>提示词 (Prompt)</label>
<textarea name="prompt" rows="3" required placeholder="描述你想生成的图像..."><?= $_POST['prompt'] ?? '' ?></textarea>
</div>
<div class="form-group">
<label>负面提示词 (Negative Prompt)</label>
<textarea name="negative_prompt" rows="2" placeholder="不想出现的元素..."><?= $_POST['negative_prompt'] ?? '' ?></textarea>
</div>
<div class="form-group">
<label>尺寸</label>
<select name="width">
<option value="512">512x512</option>
<option value="768">768x768</option>
<option value="1024">1024x1024</option>
</select>
</div>
<button type="submit">✨ 生成图像</button>
</form>
</div>
<div>
<h3>生成的图像</h3>
<div class="gallery">
<?php foreach ($images as $image): ?>
<div>
<img src="<?= $image ?>" alt="AI生成图像">
<a href="<?= $image ?>" download>下载</a>
</div>
<?php endforeach; ?>
</div>
</div>
</div>
</body>
</html>
使用Composer包
composer require openai-php/client
<?php
require_once 'vendor/autoload.php';
use OpenAI\Client;
$yourApiKey = 'your-api-key';
$client = OpenAI::client($yourApiKey);
$result = $client->images()->create([
'model' => 'dall-e-3',
'prompt' => 'A cute baby sea otter',
'n' => 1,
'size' => '1024x1024',
'response_format' => 'url',
]);
foreach ($result->data as $data) {
// 下载图像
$imageContent = file_get_contents($data->url);
file_put_contents('otter_' . time() . '.png', $imageContent);
}
?>
推荐的最佳实践
- 缓存机制:缓存生成的图像,避免重复调用API
- 队列系统:使用Redis或数据库实现任务队列
- 错误处理:完善的异常捕获和日志记录
- 限流保护:防止API滥用
- 图像处理:集成GD库或Imagick进行后处理
常见API提供商
- Stability AI:Stable Diffusion API
- OpenAI:DALL-E 3 API
- Replicate:多种AI模型
- Hugging Face:开源模型API
- 百度文心一言:国内可用的AI绘画
选择哪个方案取决于你的具体需求、预算和技术栈,建议从简单的API调用开始,逐步扩展到更复杂的方案。
版权声明:足球直播
足球直播
足球直播
足球直播
足球直播
中超直播
中超直播
中超直播
中超直播
中超直播
英超直播
英超直播
英超直播
英超直播
英超直播
德甲直播
德甲直播
德甲直播
德甲直播
德甲直播
西甲直播
西甲直播
西甲直播
西甲直播
西甲直播
意甲直播
意甲直播
意甲直播
意甲直播
意甲直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
篮球直播
篮球直播
篮球直播
篮球直播
篮球直播
足球直播
足球直播
足球直播
足球直播
足球直播
中超直播
中超直播
中超直播
中超直播
中超直播
英超直播
英超直播
英超直播
英超直播
英超直播
德甲直播
德甲直播
德甲直播
德甲直播
德甲直播
西甲直播
西甲直播
西甲直播
西甲直播
西甲直播
意甲直播
意甲直播
意甲直播
意甲直播
意甲直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
篮球直播
篮球直播
篮球直播
篮球直播
篮球直播
足球直播
足球直播
足球直播
足球直播
足球直播
中超直播
中超直播
中超直播
中超直播
中超直播
英超直播
英超直播
英超直播
英超直播
英超直播
德甲直播
德甲直播
德甲直播
德甲直播
德甲直播
西甲直播
西甲直播
西甲直播
西甲直播
西甲直播
意甲直播
意甲直播
意甲直播
意甲直播
意甲直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
篮球直播
篮球直播
篮球直播
篮球直播
篮球直播