package com.sunwin.robot2ips.util;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.*;

/**
 * @author 作者：Sky
 * @name Base64.java
 * @time 时间：2017-12-24 下午09:11:35
 * @description 描述：图片base64转码器
 */
public class Base64Util {

    /**
     * 图片转化成base64字符串
     */
    public static String imageBase64(String imgPath) {//将图片文件转化为字节数组字符串，并对其进行Base64编码处理
        //String imgFile = "D:\\tupian\\a.jpg";//待处理的图片
        InputStream in = null;
        byte[] data = null;
        //读取图片字节数组
        try {
            in = new FileInputStream(imgPath);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(data);//返回Base64编码过的字节数组字符串
    }

    /**
     * 图片流转化成base64字符串
     */
    public static String imageBase64(InputStream in) {
        byte[] data = null;
        //读取图片字节数组
        try {
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(data);//返回Base64编码过的字节数组字符串
    }

    public static byte[] getBase64ByteCode(String imgPath) {
        InputStream in = null;
        byte[] data = null;
        //读取图片字节数组
        try {
            in = new FileInputStream(imgPath);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return data;
    }

    public static byte[] getByteByBase64Code(String base64Code) {
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            return decoder.decodeBuffer(base64Code);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String byteImageCodeToStr(byte[] data) {
        //对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(data);//返回Base64编码过的字节数组字符串
    }

    /**
     * base64字符串转化成图片
     */
    public static boolean generateImage(String imgCode, String imgPath) {   //对字节数组字符串进行Base64解码并生成图片
        if (imgCode == null) //图像数据为空
            return false;
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            //Base64解码
            byte[] b = decoder.decodeBuffer(imgCode);
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {//调整异常数据
                    b[i] += 256;
                }
            }
            //生成jpeg图片
            //String imgFilePath = "C:\\Users\\sunwin\\Desktop\\dong2.jpg";//新生成的图片
            OutputStream out = new FileOutputStream(imgPath);
            out.write(b);
            out.flush();
            out.close();
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 用图片二进制码生成图片
     */
    public static boolean generateImage(byte[] b, String imgPath) {
        if (b == null) //图像数据为空
            return false;
        try {
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {//调整异常数据
                    b[i] += 256;
                }
            }
            //生成图片
            OutputStream out = new FileOutputStream(imgPath);
            out.write(b);
            out.flush();
            out.close();
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * @Description: 使用Base64对字符串进行解码
     * @Param: [s]
     * @Author: shiwn
     * @Date: 2020/6/16 15:42
     */
    public static String getFromBASE64(String s) {
        byte[] b = null;
        String result = null;
        if (s != null) {
            BASE64Decoder decoder = new BASE64Decoder();
            try {
                b = decoder.decodeBuffer(s);
                result = new String(b, "utf-8");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 计算图片大小
     *
     * @param: base64编码
     * @return:
     * @author machao
     * @date: 2021/9/9 15:38
     */
    public static Integer imageSize(String image) {
        String str = image;
        if (image.contains("data:image/png;base64,")) {
            // 1.需要计算文件流大小，首先把头部的data:image/png;base64,（注意有逗号）去掉。
            str = image.substring(22);
        }
        //2.找到等号，把等号也去掉
        Integer equalIndex = str.indexOf("=");
        if (str.indexOf("=") > 0) {
            str = str.substring(0, equalIndex);
        }
        //3.原来的字符流大小，单位为字节
        Integer strLength = str.length();
        //4.计算后得到的文件流大小，单位为字节
        Integer size = strLength - (strLength / 8) * 2;
        return size;
    }



    /**
     * 本地文件（图片、excel等）转换成Base64字符串
     *
     * @param imgPath
     */
    public static String convertFileToBase64(String imgPath) {
        byte[] data = null;
        // 读取图片字节数组
        try {
            InputStream in = new FileInputStream(imgPath);
            System.out.println("文件大小（字节）="+in.available());
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 对字节数组进行Base64编码，得到Base64编码的字符串
        BASE64Encoder encoder = new BASE64Encoder();
        String base64Str = encoder.encode(data);
        return base64Str;
    }
}
