好久不见各位,最近我也是已经实习有一段时间了,博客也有一段时间没有更新了,但是最近着手完成了一个图片生成的项目,后端使用的是Springboot,在图片处理使用了最近很火的黑森林研究所的Flux模型,如何使用Java来访问和调用这个接口呢,接下来我就来分享一下。
首先你需要在yml文件里进行比较隐私信息的配置:
image:
edit:
tokens:
single-deduct: 100
blend-deduct: 50
api: https://api.bfl.ai/v1/flux-kontext-max
key: your_key
blend-api: https://api.bfl.ai/v1/flux-kontext-pro
key是需要你去官网自行注册的,具体注册方法可以参考:
Flux爆火,全网最全面最详细的Flux使用教程!-CSDN博客
接下来就是最重要的接口部分:
/**
* 核心方法:调用Flux API处理图片
* @param imageData 图片数据(可以是URL或base64字符串)
* @param prompt 提示词
* @param isBase64 是否为base64格式
* @param aspectRatio 宽高比字符串,格式为 "width:height",为null时不传递
*/
private String processImageWithFluxApi(String imageData, String prompt, boolean isBase64, String aspectRatio) throws Exception {
FluxRequestDTO request = new FluxRequestDTO(prompt, imageData);
if (aspectRatio != null) {
request.setAspectRatio(aspectRatio);
}
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.set("x-key", fluxApiKey);
HttpEntity<FluxRequestDTO> entity = new HttpEntity<>(request, headers);
ResponseEntity<FluxResponseDTO> response = restTemplate.postForEntity(
fluxApiUrl, entity, FluxResponseDTO.class);
if (response.getStatusCode() != HttpStatus.OK || response.getBody() == null) {
throw new RuntimeException("Flux API调用失败");
}
FluxResponseDTO fluxResponse = response.getBody();
String taskId = fluxResponse.getId();
String pollingUrl = fluxResponse.getPollingUrl();
if (taskId == null || pollingUrl == null) {
throw new RuntimeException("无效的Flux API响应");
}
return pollFluxResult(pollingUrl);
}
private String pollFluxResult(String pollingUrl) throws Exception {
int maxRetries = 60;
int retryInterval = 5;
for (int attempt = 0; attempt < maxRetries; attempt++) {
ResponseEntity<FluxResponseDTO> response = restTemplate.getForEntity(
pollingUrl, FluxResponseDTO.class);
if (response.getStatusCode() == HttpStatus.OK && response.getBody() != null) {
FluxResponseDTO fluxResponse = response.getBody();
String status = fluxResponse.getStatus();
if ("Ready".equals(status)) {
if (fluxResponse.getResult() != null &&
fluxResponse.getResult().getSample() != null) {
return fluxResponse.getResult().getSample();
}
throw new RuntimeException("未获取到处理后的图片URL");
} else if ("failed".equals(status)) {
throw new RuntimeException("Flux处理任务失败");
}
}
Thread.sleep(retryInterval * 1000);
}
throw new RuntimeException("处理超时,请稍后重试");
}
这段代码主要实现了与Flux API交互处理图片的功能,具体作用如下:
1. 核心方法`processImageWithFluxApi`负责构建请求并调用Flux API: - 根据传入的图片数据(URL或base64)、提示词等参数创建请求对象 - 设置请求头信息,包括内容类型和API密钥 - 发送POST请求到Flux API获取处理任务 - 从响应中提取任务ID和轮询URL,调用轮询方法获取最终结果
2. 辅助方法`pollFluxResult`负责轮询获取处理结果: - 设置最大重试次数(60次)和重试间隔(5秒) - 循环向轮询URL发送GET请求查询任务状态 - 当任务状态为"Ready"时,返回处理后的图片样本 - 当任务状态为"failed"时,抛出处理失败异常 - 超过最大重试次数仍未完成时,抛出超时异常 整体流程实现了一个异步API调用模式:先提交处理任务,然后通过轮询方式等待处理完成并获取结果,适用于处理时间不确定的图片处理场景。
这就是这次分享,希望可以对你们有帮助,以后会提高发的频率的。