代码示例 / Node / PHP

php使用图片编辑demo


<?php

// 引入Composer自动加载器

require_once 'vendor/autoload.php';



use GuzzleHttp\Client;



// 测试用的变量定义

$model = "flux-kontext-max";

$queue = ['prompt' => '改成蓝色'];

$correctedImg = '场景1.png'; // 图像文件路径



// 创建Guzzle HTTP客户端

$client = new Client();



// 构建multipart数据数组 - 根据Apifox的参数

$multipart = [

    [

        'name' => 'model',

        'contents' => $model

    ],

    [

        'name' => 'prompt',

        'contents' => $queue['prompt']

    ],

    [

        'name' => 'n',

        'contents' => '1'

    ],

    [

        'name' => 'size',

        'contents' => '1024x1024'

    ],

    [

        'name' => 'response_format',

        'contents' => 'b64_json'

    ]

];



// 如果有图像文件,添加文件数据

if ($correctedImg !== false && file_exists($correctedImg)) {

    $multipart[] = [

        'name' => 'image',

        'contents' => fopen($correctedImg, 'r'),

        'filename' => basename($correctedImg),

        'headers' => [

            'Content-Type' => 'image/png'

        ]

    ];

    echo "图像文件已添加: " . $correctedImg . "\n";

} else {

    echo "警告: 图像文件不存在或路径错误: " . $correctedImg . "\n";

}



// 输出请求信息

echo "模型: " . $model . "\n";

echo "提示词: " . $queue['prompt'] . "\n";

echo "图像文件: " . $correctedImg . "\n\n";



// 发送HTTP请求

try {

    echo "正在发送请求到CokeAPIAI...\n";

    

    $response = $client->request('POST', 'https://www.cokeapi.com/v1/images/edits', [

        'headers' => [

            'Authorization' => 'Bearer sk-你的key',

            'Accept' => 'application/json'

        ],

        'multipart' => $multipart,

        'timeout' => 60, // 增加超时时间到60秒

        'debug' => true // 开启debug模式查看请求详情

    ]);

    

    // 获取响应

    $statusCode = $response->getStatusCode();

    $responseBody = $response->getBody()->getContents();

    

    echo "请求成功!\n";

    echo "状态码: " . $statusCode . "\n";

    echo "响应内容:\n" . $responseBody . "\n";

    

    // 解析JSON响应

    $responseData = json_decode($responseBody, true);

    if (isset($responseData['data']) && isset($responseData['data'][0]['url'])) {

        echo "\n生成的图片URL: " . $responseData['data'][0]['url'] . "\n";

    }

    

} catch (GuzzleHttp\Exception\ClientException $e) {

    echo "客户端错误 (4xx): " . $e->getMessage() . "\n";

    echo "响应内容: " . $e->getResponse()->getBody()->getContents() . "\n";

} catch (GuzzleHttp\Exception\ServerException $e) {

    echo "服务器错误 (5xx): " . $e->getMessage() . "\n";

    echo "响应内容: " . $e->getResponse()->getBody()->getContents() . "\n";

} catch (Exception $e) {

    echo "请求失败: " . $e->getMessage() . "\n";

}