
随着大模型的升级迭代,现在越来越多的人都开始接入API接口了,尤其是JAVA的同学们,上一篇文章介绍了,从零搭建一个环境,用于调用openai的key,进行访问AI接口,进行一些对话的功能,本篇文章主要介绍生成图片的接口。希望可以帮助到正在学习spring.ai的同学一些参考。
OpenAiImageClient 的核心功能OpenAiImageClient 是 Spring AI 框架中用于与 OpenAI 图像生成接口(如 DALL·E)交互的客户端工具,提供以下核心能力:
application.yml)或代码动态覆盖参数,适配不同场景需求OpenAiImageClient 的使用方法在 application.yml 中配置 OpenAI 的 API 密钥及默认参数:
spring:
  ai:
    openai:
      api-key: sk-xxxxxxxxxxxxxxxx  # 替换为实际 API 密钥
      base-url: https://api.openai.com/v1  # OpenAI 接口地址
      image:
        options:
          model: gpt-4-dalle  # 使用的模型(如 DALL·E)
          quality: hd         # 图像质量(标准/高清)
          n: 1               # 生成图像数量
          height: 1024        # 图像高度
          width: 1024         # 图像宽度此配置会作为全局默认值生效9。
在控制器中注入 OpenAiImageClient,并调用其生成图像的接口:
@RestController
public class ImageController {
    @Resource
    private OpenAiImageClient openAiImageClient;
    @RequestMapping("/ai/image")
    public Object generateImage(@RequestParam String msg) {
        // 构造请求:包含文本提示和配置选项
        ImagePrompt prompt = new ImagePrompt(
            msg, 
            OpenAiImageOptions.builder()
                .withQuality("hd")
                .withN(1)
                .withHeight(1024)
                .withWidth(1024)
                .build()
        );
        
        // 调用 API 生成图像
        ImageResponse response = openAiImageClient.call(prompt);
        
        // 提取结果中的图像 URL
        String imageUrl = response.getResult().getOutput().getUrl();
        return imageUrl;
    }
}ImagePrompt 封装了用户输入的文本提示(如 "一只太空猫")及配置参数。call() 方法同步发送请求,返回 ImageResponse 对象,包含生成图像的元数据和 URL9。若需在代码中动态修改配置(如临时调整图像尺寸):
ImageResponse response = openAiImageClient.call(
    new ImagePrompt(msg, OpenAiImageOptions.builder()
        .withQuality("standard")
        .withWidth(512)
        .withHeight(512)
        .build()
);注意:代码中的配置优先级高于全局配置文件9。
OpenAiImageClient 将用户输入的文本和配置参数封装为符合 OpenAI API 规范的 JSON 请求体。RestTemplate 或 WebClient 发送 POST 请求至 OpenAI 的 /images/generations 端点。Authorization: Bearer {api-key}9。ImageResponse 对象。ImageResponse 中提取图像 URL 或二进制数据,供业务层处理(如存储、展示)9。n(生成数量)参数。@Async)提升用户体验package org.example;
import jakarta.annotation.Resource;
import org.springframework.ai.image.Image;
import org.springframework.ai.image.ImagePrompt;
import org.springframework.ai.image.ImageResponse;
import org.springframework.ai.openai.OpenAiChatClient;
import org.springframework.ai.openai.OpenAiImageClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class AiController {
    @Resource
    private OpenAiChatClient aiClient;
    @Autowired
    private OpenAiImageClient openAiImageClient;
    @PostMapping("/ask")
    public String askQuestion(@RequestBody String prompt) {
        return aiClient.call(prompt);
    }
    @GetMapping("/get")
    public String GetInfo() {
        return aiClient.call("JAVA学习路线");
    }
    /**
     * 生成图片
     */
    @GetMapping(value = "generateImage",produces = "text/html")
    public String generateImage(String prompt) {
        ImageResponse response = openAiImageClient.call(new ImagePrompt(prompt));
        Image outImage = response.getResult().getOutput();
        //url地址
        String url = outImage.getUrl();
        return "<img src='"+url+"'/>";
    }
}

生成图片需要注意风险点,不能违规生成图片,以及进行测试的时候,注意到描述提示词的用法,表达的越仔细要求的token越多,现在使用这个key对于token的消耗还是很大的。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。