php调用阿里通义万相-图像背景生成与文生图api记录
想用php接入阿里通义万相的文生图功能和图像背景生成api来接入自己的业务中,研究了一下,记录一下过程
1、申请网址
https://dashscope.console.aliyun.com/model
没有权限的需要自己申请权限,教程-》https://blog.bfw.wiki/user12305/16947548781987640055.html
通义万相主模型为wanx-v1,但是下面又有一些列微调模型,比如生成产品背景图的模型wanx-background-generation-v2,人物风格图片:wanx-style-repaint-v1,还有cosplay动漫人物照片生成,模型是:wanx-style-cosplay-v1
通义万相-图像背景生成膜性能wanx-background-generation-v2是指定一个商品产品图片,通过api和文字描述,生成一个虚拟背景合成产品的图片,效果如下:
wanx-background-generation-v2
而通义万相通用文本生成图片api是根据文本生成任意图片
wanx-style-cosplay-v1
wanx-style-repaint-v1
2、php接入,此接口是http的异步提交的,就是提交文生图任务后,通过任务id来查询任务结果。
我们以主模型wanx-v1为例,文本描述为:一只奔跑的猫,风格是3d风格,支持的风格如下:
php示例代码:
<?php // 提交任务的函数 function submitText2ImageTask($apiKey, $prompt, $style, $size, $n, $seed) { $url = 'https://dashscope.aliyuncs.com/api/v1/services/aigc/text2image/image-synthesis'; // 构建请求的Header和Body $headers = array( 'Authorization: Bearer ' . $apiKey, 'X-DashScope-Async: enable', 'Content-Type: application/json' ); $postData = array( 'model' => 'wanx-v1', 'input' => array( 'prompt' => $prompt ), 'parameters' => array( 'style' => $style, 'size' => $size, 'n' => $n, 'seed' => $seed ) ); $jsonData = json_encode($postData); // 初始化cURL会话 $ch = curl_init($url); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 执行HTTP请求 $response = curl_exec($ch); curl_close($ch); // 解析返回的json响应 $responseArray = json_decode($response, true); // 返回作业ID return $responseArray['output']['task_id'] ?? null; } // 查询任务状态的函数 function queryTaskStatus($apiKey, $task_id) { $url = "https://dashscope.aliyuncs.com/api/v1/tasks/" . $task_id; // 构建请求的Header $headers = array( 'Authorization: Bearer ' . $apiKey ); // 初始化cURL会话 $ch = curl_init($url); curl_setopt($ch, CURLOPT_HTTPGET, true); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 执行HTTP请求 $response = curl_exec($ch); curl_close($ch); // 解析返回的json响应 $responseArray = json_decode($response, true); // 返回任务状态和图片URL(如果任务成功并生成了图片) return $responseArray; } // 调用提交任务函数 $apiKey = ''; // 替换为你的API-KEY $task_id = submitText2ImageTask($apiKey, '一只奔跑的猫', '<3d cartoon>', '1024*1024', 1, 42); // 如果成功获取到任务ID,则可以进一步查询任务状态 if ($task_id) { echo "任务提交成功,任务ID: {$task_id}\n"; } else { echo "任务提交失败\n"; } // 假设这是一个之前提交任务后获得的任务ID //$task_id = '<YOUR-TASK-ID>'; // 调用查询任务状态函数 $status = queryTaskStatus($apiKey, $task_id); echo "任务状态查询结果:\n"; print_r($status); ?>
生成的图片
网友评论0