前些时候发现腾讯云新出了个AI绘画,就想试着能否写一个网页代码实现AI绘画的功能
在AI 的帮助下,实现了此功能,但是有些地方有待完善,目前可以实现文生图的功能。
本项目Github地址:suyin101/tencentaidraw: 对接腾讯云官方接口AI绘画做的 (github.com)
演示地址:苏音 | 苏音资源网 - 提供免费资源分享-我爱分享网 (suyin66.com)
先放出代码吧~
index.php
AI绘画--苏音
AI绘画苏音
剩余次数:
draw.php
setEndpoint("aiart.tencentcloudapi.com");
// 实例化一个 ClientProfile 对象,可选的,没有特殊需求可以跳过
$clientProfile = new ClientProfile();
$clientProfile->setHttpProfile($httpProfile);
// 实例化要请求产品的 Client 对象
$client = new AiartClient($cred, "ap-shanghai", $clientProfile);
// 实例化一个 TextToImageRequest 对象
$req = new TextToImageRequest();
$userInput = $_GET['prompt'];
$styles = $_GET['Styles'];
// 检查风格参数是否为整数数字
if (!is_numeric($styles)) {
// 风格参数无效,返回错误响应
$response = array(
'error' => 'Invalid Styles parameter'
);
header('Content-Type: application/json');
echo json_encode($response);
exit;
}
$params = array(
"Prompt" => $userInput,
"Styles" => array(strval($styles)) // 将风格参数转换为字符串
);
$req->fromJsonString(json_encode($params));
// 返回的 resp 是一个 TextToImageResponse 对象,与请求对象对应
$resp = $client->TextToImage($req);
// 输出 json 格式的字符串响应
header('Content-Type: application/json');
echo $resp->toJsonString();
} catch (TencentCloudSDKException $e) {
echo $e;
}
proxy.php
'Invalid Styles parameter'
);
header('Content-Type: application/json');
echo json_encode($response);
exit;
}
// 构建请求 URL,包括风格参数
$requestUrl = $apiUrl . '?prompt=' . urlencode($prompt) . '&Styles=' . urlencode($styles);
// 发起请求并获取响应
$response = file_get_contents($requestUrl);
// 将响应发送回前端
header('Content-Type: application/json');
echo $response;
index.php 首页文件
draw.php 接口代码
proxy.php 代理接口文件
把以上三个文件都放到网站中,并修改相应内容
且需要安装Composer依赖
具体可以参考腾讯云的文档和这个
API Explorer - 云 API - 控制台 (tencent.com)
PHP-SDK 中心-腾讯云 (tencent.com)
宝塔Linux面板安装Composer依赖管理工具与PHP依赖包的方法宝塔面板安装composer苏音资源的博客-CSDN博客