package cn.hanghui.outapi.platform.common.utils;

import sun.misc.BASE64Encoder;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Base64;

/**
 * @author shisl
 * @package cn.hanghui.outapi.platform.common.utils
 * @class ImageUtil
 * @date 2024/8/1 下午4:39
 * @description
 */
public class ImageUtil {

    /*
     * 把url的图片下载下来并转为Base64
     * */
    public static String getImageBase64FromUrl(String netUrl) {
        /*特别定制
         * 因为https://noise.hz-hanghui.com:8088的服务器 无法访问https的图片，所以在这里进行切割
         * */
        netUrl = netUrl.replace("https://tx.hz-hanghui.com:8088/hanghui-openapi/", "http://127.0.0.1:8109/hanghui-openapi/");
        return tranUrlToBase64String(netUrl);
    }

    public static String tranUrlToBase64String(String imgStr) {
        InputStream inputStream = null;
        ByteArrayOutputStream outputStream = null;
        byte[] buffer = null;
        try {
            //判断网络链接图片文件/本地目录图片文件
            if (imgStr.startsWith("http://") || imgStr.startsWith("https://")) {
                // 创建URL
                URL url = new URL(imgStr);
                // 创建链接
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("GET");
                conn.setConnectTimeout(5000);
                inputStream = conn.getInputStream();
                outputStream = new ByteArrayOutputStream();
                // 将内容读取内存中
                buffer = new byte[1024];
                int len = -1;
                while ((len = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, len);
                }
                buffer = outputStream.toByteArray();
            } else {
                inputStream = new FileInputStream(imgStr);
                int count = 0;
                while (count == 0) {
                    count = inputStream.available();
                }
                buffer = new byte[count];
                inputStream.read(buffer);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    // 关闭inputStream流
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (outputStream != null) {
                try {
                    // 关闭outputStream流
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        // 对字节数组Base64编码
        return Base64.getEncoder().encodeToString(buffer);
    }
}
