当前位置: 首页 > news >正文

使用请求调用本地部署的stable-diffusion接口

stable-diffusion-webui项目地址
具体部署教程请去B站寻找或者直接使用整合包
这里直接编写工具类

public class StableDiffusionUtil {
    private static final String BASE_URL = "http://127.0.0.1:7860";
    private static final OkHttpClient CLIENT = new OkHttpClient();
    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
    /**
     * 获取可用模型列表
     *
     * @return 模型列表的 JSON 字符串
     * @throws IOException 如果请求失败
     */
    public static List<ModelInfo> listModels() throws IOException {
        Request request = new Request.Builder()
                .url(BASE_URL + "/sdapi/v1/sd-models")
                .get()
                .build();

        try (Response response = CLIENT.newCall(request).execute()) {
            if (response.isSuccessful()) {
                String jsonResponse = response.body().string();
                // 将 JSON 字符串解析为 ModelInfo 对象列表
                return OBJECT_MAPPER.readValue(jsonResponse, new TypeReference<List<ModelInfo>>() {});
            } else {
                throw new IOException("请求失败: " + response.code());
            }
        }
    }

    /**
     * 生成图片并保存
     *
     * @param prompt          生成图片的描述
     * @param negativePrompt  负面描述
     * @param steps           生成步骤
     * @param cfgScale        CFG 参数
     * @param width          图片宽度
     * @param height         图片高度
     * @param samplerIndex   采样器
     * @param modelCheckpoint 模型名称
     * @param outputFilePath  保存图片的文件路径
     * @throws IOException 如果请求失败或保存图片失败
     */
    public static byte[] generateImage(String prompt, String negativePrompt, int steps, int cfgScale,
                                       int width, int height, String samplerIndex, String modelCheckpoint) throws IOException {
        // 请求参数
        String json = "{"
                + "\"prompt\": \"" + prompt + "\","
                + "\"negative_prompt\": \"" + negativePrompt + "\","
                + "\"steps\": " + steps + ","
                + "\"cfg_scale\": " + cfgScale + ","
                + "\"width\": " + width + ","
                + "\"height\": " + height + ","
                + "\"sampler_index\": \"" + samplerIndex + "\","
                + "\"sd_model_checkpoint\": \"" + modelCheckpoint + "\""
                + "}";

        RequestBody body = RequestBody.create(json, MediaType.parse("application/json; charset=utf-8"));
        Request request = new Request.Builder()
                .url(BASE_URL + "/sdapi/v1/txt2img")
                .post(body)
                .build();

        try (Response response = CLIENT.newCall(request).execute()) {
            if (response.isSuccessful()) {
                String jsonResponse = response.body().string();
                String imageBase64 = jsonResponse.split("\"images\":\\[\"")[1].split("\"")[0];

                // 解码 Base64 图片
                byte[] imageBytes = Base64.getDecoder().decode(imageBase64);
                ByteArrayInputStream bis = new ByteArrayInputStream(imageBytes);
                BufferedImage image = ImageIO.read(bis);

                // 将图片转换为二进制数组
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                ImageIO.write(image, "png", baos);
                return baos.toByteArray();
            } else {
                throw new IOException("请求失败: " + response.code());
            }
        }
    }

    /**
     * 切换模型
     *
     * @param modelCheckpoint 模型名称
     * @throws IOException 如果请求失败
     */
    public static void switchModel(String modelCheckpoint) throws IOException {
        // 更新模型配置
        String json = "{"
                + "\"sd_model_checkpoint\": \"" + modelCheckpoint + "\""
                + "}";

        RequestBody body = RequestBody.create(json, MediaType.parse("application/json; charset=utf-8"));
        Request request = new Request.Builder()
                .url(BASE_URL + "/sdapi/v1/options")
                .post(body)
                .build();

        try (Response response = CLIENT.newCall(request).execute()) {
            if (response.isSuccessful()) {
                System.out.println("模型已切换到 " + modelCheckpoint);
            } else {
                throw new IOException("请求失败: " + response.code());
            }
        }
    }




}

调用工具类实现

@Autowired
    private SysOssService ossService;
    @Test
    void test8() throws Exception {

        String prompt = "A futuristic city with flying cars, highly detailed, 4k";
        String negativePrompt = "blurry, low quality, distorted, text";
        int steps = 30;
        int cfgScale = 7;
        int width = 512;
        int height = 512;
        String samplerIndex = "Euler a";
        String outputFilePath = "output.png";
        String modelInfo="anything-v5-PrtRE.safetensors [7f96a1a9ca]";
        // 调用方法生成图片
        byte[] imageBytes= StableDiffusionUtil.generateImage(prompt, negativePrompt, steps, cfgScale, width, height, samplerIndex, modelInfo);
        String fileName = "generated_image.png"; // 文件名
        String contentType = "image/png"; // 文件类型
        SysOssDTO ossDTO = ossService.upload(imageBytes, fileName, contentType);

        // 打印上传结果
        System.out.println("文件上传成功,访问路径: " + ossDTO.getUrl());
    }

相关文章:

  • 从零开始实现 C++ TinyWebServer 处理请求 HttpRequest类详解
  • 3D引擎:Three.js有什么有什么优缺点?
  • 数据人的进阶之路:四年数仓实践与成长思考
  • Elasticsearch + Docker:实现容器化部署指南
  • SpringBoot3使用CompletableFuture时java.util.ConcurrentModificationException异常解决方案
  • 优先级与环境变量的艺术:驾驭 Linux 系统的核心
  • Vue 入门到实战 五
  • Mac | Excel | 列数改为和行数一样用数字表示
  • MyBatis-Plus(SpringBoot版)学习第一讲:简介入门案例
  • Rocky9.2 编译安装Intel系列无线网卡驱动
  • RK3568 I2C底层驱动详解
  • 查找单入口空闲区域[A卷-hw_od]
  • 博弈论中的均衡精炼:完美贝叶斯均衡、序贯均衡与颤抖手均衡详解
  • 定义时钟约束
  • 游戏引擎学习第176天
  • leetcode699-修剪二叉搜索树
  • Agent:大模型中的智能“函数”
  • 【Vue3入门1】02- vue3的基本操作(上)
  • 【商城实战(57)】商城数据迁移与升级实战:开启电商新征程
  • 算法|2025最强优化算法
  • 一热就出汗 VS 热死都不出汗的人,哪个更健康?
  • 城管给商户培训英语、政银企合作纾困,上海街镇这样优化营商环境
  • 美联储宣布维持基准利率不变
  • 美国与胡塞武装达成停火协议,美伊相向而行?
  • “子宫内膜异位症”相关论文男性患者样本超六成?福建省人民医院发布情况说明
  • 新疆生产建设兵团草湖项目区副主任宋全伟接受审查调查