package com.github.novicezk.midjourney.util;

import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.util.Base64;

@Slf4j
public class DataURIUtil {

    /**
     * 将在线图片地址转换成BASE64编码的 DataURI 形式
     * @param imageUrl
     * @return
     */
    public static String getBase64FromImageUrl(String imageUrl) {
        try {
            URL url = new URL(imageUrl);
            InputStream inputStream = url.openStream();
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            // 将图片数据读取到字节数组输出流
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }

            // 将字节数组输出流中的图片数据进行 Base64 编码
            byte[] imageBytes = outputStream.toByteArray();
            String base64Data = Base64.getEncoder().encodeToString(imageBytes);
            // 构建 Data URI
            String last = imageUrl.substring(imageUrl.lastIndexOf(".") + 1);
            String mimeType = "image/" + last; // 替换为对应的 MIME 类型，根据图片类型可能是 "image/jpeg" 或 "image/gif" 等
            String dataURI = "data:" + mimeType + ";base64," + base64Data;
            return dataURI;
        } catch (Exception e) {
            log.error("将在线图片url转换成base64异常：{}", e);
        }
        return "";
    }
}
