在开发基于 OpenAI 的图像生成 API 的应用程序时,我们有时会遇到一些兼容性问题,特别是当某些 API 实现不支持 b64_json 输出格式时。为了让这些 API 能够在支持 b64_json 的环境中(如 Open WebUI)正常工作,我开发了一个简单的 PHP 脚本,用于将图像 URL 转换为 Base64 编码格式。
在本文中,我将分享这段代码,并解释其工作原理。
背景
OpenAI 的图像生成 API 通常会返回图像的 URL 或直接返回 Base64 编码的图像数据 (b64_json)。然而,某些第三方或兼容的 API 实现可能不支持 b64_json 输出格式,这可能会在某些环境中导致问题。
为了解决这个问题,我编写了一个 PHP 脚本,它可以自动将 API 返回的图像 URL 转换为 b64_json 格式,从而确保与 Open WebUI 等需要 Base64 编码图像的环境兼容。
代码实现
以下是 PHP 代码的实现:
<?php
// Set the API endpoint URL
$URL = "https://api.siliconflow.cn/v1/images/generations";
// Get necessary fields and check request
$authorizationHeader = null;
foreach (getallheaders() as $name => $value) {
if (strtolower($name) === 'authorization') {
$authorizationHeader = $value;
break;
}
}
if (!$authorizationHeader) {
http_response_code(400);
echo json_encode(['error' => 'Missing Authorization header']);
exit;
}
$requestData = json_decode(file_get_contents('php://input'), true);
if (json_last_error() !== JSON_ERROR_NONE) {
http_response_code(400);
echo json_encode(['error' => 'Invalid JSON input']);
exit;
}
// Send request to API endpoint
$ch = curl_init($URL);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Authorization: '. $authorizationHeader,
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($requestData));
$response = curl_exec($ch);
// Check response
if (curl_errno($ch)) {
die('cURL error on request: ' . curl_error($ch));
}
// Get response code
$responseCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// Close cURL handle
curl_close($ch);
// Check response code
http_response_code($responseCode);
if ($responseCode !== 200) {
echo $response;
exit;
} else {
$responseData = json_decode($response, true);
if (json_last_error() !== JSON_ERROR_NONE) {
http_response_code(500);
echo json_encode(['error' => 'Invalid JSON response']);
exit;
}
}
// Convert response to b64_json if necessary
if (isset($requestData['response_format']) && $requestData['response_format'] === 'b64_json' && !isset($responseData['data'][0]['b64_json'])) {
if (!isset($responseData['images'][0]['url'])) {
http_response_code(500);
echo json_encode(['error' => 'Missing image URL field in response']);
exit;
}
// Get data from URL
$ch = curl_init($responseData['images'][0]['url']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, false);
$data = curl_exec($ch);
if (curl_errno($ch)) {
die('cURL error on converting response to b64_json: ' . curl_error($ch));
}
curl_close($ch);
// Convert data to b64_json
$base64Data = base64_encode($data);
// Use finfo to detect MIME type
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mimeType = finfo_buffer($finfo, $data);
finfo_close($finfo);
// If MIME type is empty, default to image/png
if (empty($mimeType)) {
$mimeType = 'image/png'; // Assuming the default is PNG
}
$b64_json = 'data:' . $mimeType . ';base64,' . $base64Data;
// Add b64_json to response data
$responseData['data'][0]['b64_json'] = $b64_json;
}
echo json_encode($responseData);
代码解析
API 请求与响应处理:
- 脚本首先从请求头中提取
Authorization信息,并将其用于 API 请求。 - 然后,它解析传入的 JSON 输入,并发送请求到指定的 API 端点。
- 根据 API 的响应状态码,脚本会返回相应的错误信息或继续处理响应。
- 脚本首先从请求头中提取
Base64 编码转换:
- 如果请求中指定了
response_format为b64_json,但 API 响应中不包含b64_json字段,脚本会自动将图像 URL 转换为 Base64 编码格式。 - 使用
cURL获取图像数据,并使用base64_encode函数将其编码为 Base64 字符串。 - 通过
finfo检测图像的 MIME 类型,并构造data URI格式的b64_json字段。
- 如果请求中指定了
返回处理后的响应:
- 最后,脚本将处理后的响应数据以 JSON 格式返回。
总结
通过这段 PHP 脚本,我们可以轻松地为不支持 b64_json 输出的 OpenAI 图像生成 API 添加 Base64 编码支持。这不仅提高了 API 的兼容性,还使得它能够在 Open WebUI 等需要 Base64 编码图像的环境中无缝运行。
希望这篇博文对你在处理类似问题时有所帮助!如果你有任何问题或建议,欢迎在评论区讨论。