
package com.heyu.api.data.utils;

import com.alipay.api.internal.util.file.IOUtils;
import com.heyu.api.data.dto.ImageInfoModel;
import lombok.extern.slf4j.Slf4j;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URL;
import java.util.Base64;

@Slf4j
public class Base64Utils {

    public static ImageInfoModel getBase64ImageInfo(String base64Image) {
        ByteArrayInputStream bis =null;
        try {
            ImageInfoModel imageInfoModel = new ImageInfoModel();
            // 获取图片格式
            imageInfoModel.setMimeType(getMimeType(base64Image));
            // 去掉Base64字符串中的头部（如果有）
            if (base64Image.contains(",")) {
                base64Image = base64Image.substring(base64Image.indexOf(",") + 1);
            }

            // 解码Base64字符串
            byte[] imageBytes = Base64.getDecoder().decode(base64Image);

            // 获取图片大小（字节数）
            imageInfoModel.setSize(imageBytes.length);

            // 获取图片尺寸
            bis = new ByteArrayInputStream(imageBytes);
            BufferedImage bufferedImage = ImageIO.read(bis);
            if (bufferedImage != null) {
                imageInfoModel.setHeight(bufferedImage.getHeight());
                imageInfoModel.setWidth(bufferedImage.getWidth());

            } else {
                imageInfoModel = null;
                log.info("解析图片失败");
            }
            return imageInfoModel;
        } catch (IOException e) {
            log.info("获取图片信息异常：{}", e);
        }finally {
            try {
                if(bis != null){
                    bis.close();
                }
            } catch (IOException e) {
                log.error("IO 异常",e);
            }
        }
        return null;
    }

    private static String getMimeType(String base64Image) {
        if (base64Image == null || !base64Image.contains(",")) {
            return "未知";
        }
        String prefix = base64Image.substring(0, base64Image.indexOf(";base64,"));
        if ("data:image/png".equals(prefix)) {
            return "PNG";
        } else if ("data:image/jpeg".equals(prefix)) {
            return "JPEG";
        } else if ("data:image/gif".equals(prefix)) {
            return "GIF";
        } else if ("data:image/bmp".equals(prefix)) {
            return "BMP";
        } else {
            return "未知";
        }
    }


    /**
     * 将 base64 转化为inputStream
     */
    public static InputStream getBase64ToInputStream(String base64Image) {
        // 1. 解码 Base64 字符串为字节数组
        byte[] decodedBytes = Base64.getDecoder().decode(base64Image);

        // 2. 将字节数组包装为 InputStream
        InputStream inputStream = new ByteArrayInputStream(decodedBytes);
        return inputStream;
    }


    /**
     * 将指定URL地址中的图片文件转换为Base64格式的字符串
     *
     * @param imageUrl 图片资源的URL地址
     * @return Base64格式的字符串
     * @throws IOException 如果读取URL链接对应的字节流时出现IO异常，则会抛出该异常
     */
    public static String encodeToBase64(String imageUrl) {
        try {
            // 使用 Java 8 引入的 Base64 类获取编码器，并将 URL 对象转换为字节数组后进行编码
            return Base64.getEncoder().encodeToString(IOUtils.toByteArray(new URL(imageUrl)));
        } catch (IOException e) {
            log.error("imageUrl :" + imageUrl + " 获取base64 异常", e);
        }
        return null;
    }


    public static String encodeImageToBase64(String imagePath) {
        File file = new File(imagePath);
        try (FileInputStream imageInFile = new FileInputStream(file)) {
            byte[] imageData = new byte[(int) file.length()];
            imageInFile.read(imageData);
            return Base64.getEncoder().encodeToString(imageData);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }


    public static void main(String[] args) {
        String imagePath = "/Users/quyixiao/Desktop/Xnip2026-05-18_20-36-51.jpg";
        String base64Image = encodeImageToBase64(imagePath);
        System.out.println("Base64 Image String:");
        System.out.println(base64Image);
    }



}
