package com.yunfeiyun.agmp.common.utils.img;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Base64;

public class ImageReadUtil {

    public static final String BASE64_HEAD = "data:image/png;base64,";
    public static BufferedImage base64ConvertImage(String base64String) throws Exception {
        base64String =  base64String.split("base64,")[1];
        // 将Base64字符串解码为字节数组
        byte[] imageBytes = javax.xml.bind.DatatypeConverter.parseBase64Binary(base64String);

        // 使用ByteArrayInputStream创建输入流
        ByteArrayInputStream inputStream = new ByteArrayInputStream(imageBytes);

        // 读取输入流创建BufferedImage对象
        return ImageIO.read(inputStream);
    }
    public static String readImageToBase64(String imagePath) throws Exception{
        Path path = Paths.get(imagePath);
        byte[] imageBytes = Files.readAllBytes(path);
        return BASE64_HEAD+Base64.getEncoder().encodeToString(imageBytes);
    }

    public static BufferedImage readImageToBufferImage(String imagePath) throws Exception{
        Path path = Paths.get(imagePath);
        byte[] imageBytes = Files.readAllBytes(path);
        return ImageIO.read(new ByteArrayInputStream(imageBytes));
    }
}
