package cn.iocoder.yudao.module.contract.utils;

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

/**
 * @author：邹祥发
 * @date：2022/11/25 14:14
 * @description：转换BufferedImage数据为byte数组
 */
public class ImageUtil {

    /**
     * 转换BufferedImage 数据为byte数组
     *
     * @param image  Image对象
     * @param format image格式字符串.如"gif","png"
     * @return byte数组
     */
    public static byte[] imageToBytes(BufferedImage image, String format) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            ImageIO.write(image, format, out);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return out.toByteArray();
    }

    /**
     * 转换byte数组为Image
     *
     * @param bytes
     * @return Image
     */
    public static Image bytesToImage(byte[] bytes) {
        Image image = Toolkit.getDefaultToolkit().createImage(bytes);
        try {
            MediaTracker mt = new MediaTracker(new Label());
            mt.addImage(image, 0);
            mt.waitForAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return image;
    }

    /**
     * base64转为图片
     * @param path
     * 文件路径：到文件夹即可，代码里会在文件夹里生成对应的jpg文件
     * @param base64
     * @return
     */
    public static String base64ToJpg(String path,String base64){
        // 判断文件路径是否存在
        File filePath = new File(path);
        if (!filePath.exists()){
            filePath.mkdirs();
        }
        // 创建文件
        String jpgFile = path + File.separator + UUID.randomUUID() + ".png";
        File file = new File(jpgFile);
        boolean jpgFileExist = false;
        try {
            jpgFileExist = file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (jpgFileExist){
            // 解密
            Base64.Decoder decoder = Base64.getDecoder();
            // 去掉base64前缀 data:image/jpeg;base64,
            base64 = base64.substring(base64.indexOf(",", 1) + 1, base64.length());
            byte[] b = decoder.decode(base64);
            // 处理数据
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {
                    b[i] += 256;
                }
            }
            // 保存图片
            try {
                FileOutputStream out = new FileOutputStream(jpgFile);
                out.write(b);
                out.flush();
                out.close();
                // 写入成功返回文件路径
                return jpgFile;
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return "文件不存在";
    }

}
