本文目录导读:

对于PHP后端拼接处理绘图提示词,核心思路是将用户输入、动态参数、系统规则进行安全组合,然后传递给绘图API(如DALL-E、Midjourney API、Stable Diffusion API等)。
以下是完整的后端拼接处理方案:
基础拼接模式
<?php // 简单字符串拼接 $userInput = '一只站在树上的猫头鹰'; $style = '水彩风格'; $resolution = '4k'; $prompt = $userInput . ',' . $style . ',' . $resolution; // 结果:一只站在树上的猫头鹰,水彩风格,4k
结构化模板拼接(推荐)
<?php
class PromptBuilder {
private $templates = [
'portrait' => '{subject},{style}肖像,{lighting}光线,{details}',
'landscape' => '{subject}风景,{style},{time},{weather}',
'fantasy' => '{subject},{style}风格,{elements},{mood}氛围'
];
private $params = [];
public function setTemplate($type) {
$this->currentTemplate = $this->templates[$type] ?? '';
return $this;
}
public function setSubject($subject) {
$this->params['{subject}'] = $this->sanitize($subject);
return $this;
}
public function setStyle($style) {
$this->params['{style}'] = $this->sanitize($style);
return $this;
}
public function setExtra($key, $value) {
$this->params['{' . $key . '}'] = $this->sanitize($value);
return $this;
}
private function sanitize($text) {
// 去除可能破坏提示词的字符
return preg_replace('/[<>{}()"]/', '', $text);
}
public function build() {
$prompt = $this->currentTemplate;
foreach ($this->params as $key => $value) {
$prompt = str_replace($key, $value, $prompt);
}
return $prompt;
}
}
// 使用示例
$builder = new PromptBuilder();
$prompt = $builder->setTemplate('portrait')
->setSubject('中国水墨风格的美女')
->setStyle('工笔细描')
->setExtra('lighting', '柔和的自然光')
->setExtra('details', '丝绸衣服,扇子')
->build();
多部件智能拼接
<?php
function buildPrompt($userInput, $options = []) {
$parts = [
'main' => $userInput,
'style' => $options['style'] ?? '',
'medium' => $options['medium'] ?? '',
'lighting' => $options['lighting'] ?? '',
'color' => $options['color'] ?? '',
'composition' => $options['composition'] ?? '',
'mood' => $options['mood'] ?? '',
'quality' => $options['quality'] ?? '4k, 高细节',
'negative' => $options['negative'] ?? '' // 负向提示词
];
// 过滤空值
$parts = array_filter($parts);
// 构建正向提示词
$positive = implode(',', array_diff_key($parts, ['negative' => '']));
// 处理负向提示词
$negative = $parts['negative'] ?? '';
return [
'prompt' => $positive,
'negative_prompt' => $negative,
'raw' => $parts
];
}
// 使用
$result = buildPrompt('赛博朋克风格的猫', [
'style' => '写实',
'lighting' => '霓虹灯',
'color' => '蓝色调',
'negative' => '模糊,低质量,扭曲'
]);
规则验证与安全处理
<?php
function validateAndBuild($userInput) {
// 1. 长度限制
if (mb_strlen($userInput) > 500) {
throw new Exception('输入过长');
}
// 2. 敏感词过滤
$badWords = ['暴力', '色情', '恐怖'];
foreach ($badWords as $word) {
if (mb_strpos($userInput, $word) !== false) {
throw new Exception('包含敏感内容');
}
}
// 3. 特殊字符转义
$cleanInput = htmlspecialchars($userInput, ENT_QUOTES, 'UTF-8');
// 4. 添加系统级关键词
$systemRules = [
'safe_work' => true,
'no_watermark' => true
];
$prompt = $cleanInput;
if ($systemRules['safe_work']) {
$prompt .= ',安全内容,适宜所有年龄';
}
if ($systemRules['no_watermark']) {
$prompt .= ',无水印';
}
return $prompt;
}
API调用完整示例
<?php
// 完整流程:接收 -> 拼接 -> 验证 -> 发送API
function generateImage($userInput, $options = []) {
// 1. 构建提示词
$builder = new PromptBuilder();
$prompt = $builder->setTemplate('landscape')
->setSubject($userInput)
->setStyle($options['style'] ?? '写实')
->setExtra('time', '黄昏')
->setExtra('weather', '晴朗')
->build();
// 2. 验证
$cleanPrompt = validateAndBuild($prompt);
// 3. 构建API请求
$apiData = [
'prompt' => $cleanPrompt,
'negative_prompt' => '模糊,低质量',
'width' => 1024,
'height' => 1024,
'steps' => 20,
'cfg_scale' => 7
];
// 4. 发送到绘图API
$response = sendToDrawingAPI($apiData);
return $response;
}
function sendToDrawingAPI($data) {
$ch = curl_init('https://api.example.com/v1/images/generations');
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_HTTPHEADER => [
'Content-Type: application/json',
'Authorization: Bearer ' . API_KEY
],
CURLOPT_POSTFIELDS => json_encode($data),
CURLOPT_RETURNTRANSFER => true
]);
$response = curl_exec($ch);
curl_close($ch);
return json_decode($response, true);
}
最佳实践总结
拼接原则:
- 结构清晰:使用模板参数替换而非简单拼接
- 类型安全:区分正向/负向提示词
- 国际化:使用
mb_*函数处理多语言
安全要点:
- 输入长度限制(建议500字符以内)
- 敏感词过滤
- 特殊字符转义
- SQL注入防护(用于存储提示词模板)
性能优化:
- 缓存常用模板
- 异步处理API请求
- 批量拼接建议使用数组合并而非字符串连接
这种方式既能灵活处理各种绘图需求,又能保证系统的安全性和可维护性。