上篇文章:Spring Boot 对接文心一言 讲述了在spring boot 项目中如何集成文心一言。现在我们来做个实例,实现AI抠图。
文心一言的抠图功能通常需要通过调用文心一言的API来实现。在Spring Boot项目中,你可以通过RestTemplate或者WebClient来发起HTTP请求调用文心一言的API。
实现文心一言抠图功能:
@Service
public class AIService {
private final RestTemplate restTemplate;
@Value("${wenxin.api-key}")
private String apiKey;
@Value("${wxyy.secret-key}")
private String secretKey;
@Value("${wenxin.api-url}")
private String apiUrl;
public AIService(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
public byte[] doImageStyling(byte[] imageData) throws IOException {
HttpHeaders headers= new HttpHeaders();
headers.set("Content-Type", "application/json");
headers.set("Authorization", "Bearer " + apiKey);
// 创建请求体,这里以MultipartFile为例
MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
body.add("image", new ByteArrayResource(imageData) {
@Override
public String getFilename() {
return "image.jpg"; // 给文件命名
}
});
// 发起POST请求到文心一言的API
ResponseEntity<byte[]> response = restTemplate.exchange(
apiUrl,
HttpMethod.POST,
new HttpEntity<>(body),
byte[].class
);
// 返回处理后的图片数据
return response.getBody();
}
}
在Controller中调用AIService:
@RestController
public class ImageStylingController {
private final AIService aiService;
public ImageStylingController(AIService aiService) {
this.aiService = aiService;
}
@PostMapping("/image/stylize")
public ResponseEntity<byte[]> stylizeImage(@RequestParam("image") MultipartFile image) throws IOException {
byte[] stylizedImage = aiService.doImageStyling(image.getBytes());
return ResponseEntity.ok().body(stylizedImage);
}
}
标签:restTemplate,Spring,image,Boot,文心,aiService,public,AIService
From: https://blog.csdn.net/qq_25987725/article/details/140713962