
豆包 Doubao Image API 价格全面解析
在本篇文章中,我们将深入探讨如何在 Java 中使用 Azure OpenAI 中的 DALL·E 3 API 进行图像生成。通过使用 OkHttp 库,我们将展示如何设置和调用 API,以生成高质量的图像。本文还将包括示例代码、图片链接以及常见问题解答,帮助您全面掌握这一主题。
Azure OpenAI 是微软提供的一项服务,允许开发者借助 OpenAI 的强大模型进行自然语言处理和图像生成。其中,DALL·E 3 是一个先进的深度学习模型,专门用于根据文本描述生成图像。它在多个领域都具有广泛的应用潜力,如设计、广告和教育等。
DALL·E 3 的图像生成功能基于强大的卷积神经网络,能够理解复杂的提示并创建高分辨率的图像。这使得它成为图像生成和编辑领域的一个革命性工具。
Azure OpenAI 提供了一系列优势,包括:
Azure OpenAI 的这些特点使其成为企业和开发者在图像生成领域的一项重要工具。
使用 OkHttp 调用 DALL·E 3 API 是一个非常实用的方法。以下是一个完整的示例代码,展示了如何在 Java 中实现这一功能。
@Value("${dall-e-3.azure-openai-key}")
private String apiKey;
@Value("${dall-e-3.endpoint}")
private String endpoint;
@Value("${dall-e-3.deployment-or-model-id}")
private String modelId;
@Value("${dall-e-3.version}")
private String version;
public String generateImage(QuestionDto questionDto) {
try {
String url = endpoint + "/openai/deployments/" + modelId + "/images/generations?api-version=" + version;
// Request body
JSONObject body = new JSONObject();
body.put("prompt", questionDto.getQuestion());
body.put("size", IMG_RESOLUTION_1024.getModel());
body.put("n", 1);
body.put("quality", QUALITY_STANDARD.getModel());
body.put("style", STYLE_NATURAL.getModel());
OkHttpClient client = new OkHttpClient.Builder()
.readTimeout(25, TimeUnit.SECONDS)
.build();
Request request = new Request.Builder()
.url(url)
.post(RequestBody.create(MediaType.parse("application/json"), body.toJSONString()))
.addHeader("api-key", apiKey)
.addHeader("Content-Type", "application/json")
.build();
Response response = client.newCall(request).execute();
if (response.isSuccessful()) {
assert response.body() != null;
String responseBody = response.body().string();
JSONObject jsonResponse = JSONObject.parseObject(responseBody);
return jsonResponse.getJSONArray("data").getJSONObject(0).getString("url");
} else {
System.out.println("Error: " + response.code() + " - " + response.message());
return null;
}
} catch (IOException e) {
log.error("Error: " + e.getMessage());
return "超时连接,请重新尝试";
}
}
OkHttp 是一个高效的 HTTP 客户端,支持 HTTP/2、流式传输和连接池等特性。其简单而强大的 API,使得构建和发送 HTTP 请求变得非常容易。使用 OkHttp,开发者可以轻松处理网络请求,并在高并发场景下保持良好的性能。
处理 API 调用的响应是使用 DALL·E 3 API 的关键步骤。为了确保获得预期的结果,开发者需要正确解析响应体,并处理可能的错误。
API 调用的响应通常以 JSON 格式返回,包含生成的图像 URL 和其他相关信息。以下是解析响应的示例代码:
String responseBody = response.body().string();
JSONObject jsonResponse = JSONObject.parseObject(responseBody);
String imageUrl = jsonResponse.getJSONArray("data").getJSONObject(0).getString("url");
System.out.println("Generated Image URL: " + imageUrl);
通过解析 JSON 响应,开发者可以提取生成的图像 URL,并将其用于后续处理,如展示或保存图像。
在调用 API 时,可能会遇到网络超时、无效请求等错误。为此,建议实现错误处理和重试机制,以提高应用的可靠性。
if (!response.isSuccessful()) {
System.out.println("Error: " + response.code() + " - " + response.message());
return null;
}
通过记录错误信息并适时重试,开发者可以有效应对网络不稳定或服务器端故障带来的问题。
在选择使用 DALL·E 3 API 的地区时,需要考虑可用性和费用。某些地区可能正在收费,而其他地区则可能免费。为了确保服务的可用性,建议选择收费地区,如瑞典中部。
可以通过 Azure 官方网站查看不同地区的定价情况:Azure OpenAI 服务 – 定价。
在选择地区时,务必确保 API 调用的稳定性和服务的可用性。
除了使用 OkHttp,开发者还可以通过 Java 原生的 HttpURLConnection 类来实现 DALL·E 3 API 的调用。以下是一个简单的示例代码:
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
public class Main {
public static void main(String[] args) {
try {
String prompt = "a painting of a rubber duck in the style of Picasso";
String url = "https://api.openai.com/v1/engines/davinci/predictions";
URL apiUrl = new URL(url);
HttpURLConnection connection = (HttpURLConnection) apiUrl.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Authorization", "Bearer YOUR_OPENAI_API_KEY");
connection.setRequestProperty("Content-Type", "application/json");
connection.setDoOutput(true);
String jsonInputString = "{"prompt": "" + prompt + "", "max_tokens": 128}";
try(OutputStream os = connection.getOutputStream()) {
byte[] input = jsonInputString.getBytes("utf-8");
os.write(input, 0, input.length);
}
try(BufferedReader br = new BufferedReader(
new InputStreamReader(connection.getInputStream(), "utf-8"))) {
StringBuilder response = new StringBuilder();
String responseLine = null;
while ((responseLine = br.readLine()) != null) {
response.append(responseLine.trim());
}
String jsonResponse = response.toString();
String imageUrl = jsonResponse.split(""")[7];
System.out.println("Generated Image URL: " + imageUrl);
}
connection.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
使用 HttpURLConnection 可以避免引入额外的库,适合对依赖管理要求较严格的项目。尽管其 API 较为基础,但通过适当的封装和处理,仍然可以实现高效的 HTTP 请求。
除了 Java,Python 也是一个常用的选择。通过 OpenAI 提供的 Python SDK,可以轻松实现图像生成。以下是一个示例代码:
import base64
import matplotlib.pyplot as plt
from openai import OpenAI
from PIL import Image
from io import BytesIO
api_key = "sk-xxxxx" # replace it with your own key
def base64_to_image(base64_string):
try:
image_data = base64.b64decode(base64_string)
image_buffer = BytesIO(image_data)
image = Image.open(image_buffer)
return image
except Exception as e:
print(f"An error occurred: {e}")
return None
client = OpenAI(api_key=api_key)
response = client.images.generate(
model="dall-e-3",
prompt="A spaceship flying through the universe", # an example
size="1024x1024",
quality="standard",
n=1,
response_format='b64_json'
)
image_b64 = response.data[0].b64_json
generated_image = base64_to_image(image_b64)
if generated_image:
plt.imshow(generated_image)
plt.axis("off")
plt.show()
Python 以其简洁的语法和丰富的第三方库而闻名,非常适合快速开发和原型设计。通过 OpenAI 的 Python SDK,开发者可以轻松实现图像生成和其他 AI 任务。
通过本文的介绍,我们详细探讨了如何在 Java 中调用 DALL·E 3 API 进行图像生成。无论是使用 OkHttp 还是 HttpURLConnection,开发者都可以根据项目需求选择合适的方法。通过解析 API 响应和处理错误,确保应用的稳定性和可靠性。此外,我们还展示了 Python 中的实现示例,提供了多种选择以满足不同开发者的需求。
问:Java 中如何设置 OkHttp 的超时时间?
new OkHttpClient.Builder().readTimeout(25, TimeUnit.SECONDS).build();
问:如何处理 DALL·E 3 API 的错误响应?
问:DALL·E 3 API 支持哪些图像风格?
问:如何在 Python 中显示生成的图像?
问:是否可以在本地保存生成的图像?