package com.jiuzhekan.cbkj.common.utils;

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

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @author mjw
 * @version 1.0.0
 * @date 2020年01月07日 11:05:00
 */
public class Base64OfSunMisc {
    /**
     * 加密
     **/
    public static String toBase64(String str) {
        if (str == null) {
            str = "";
        }
        byte[] b = null;
        String s = null;
        try {
            b = str.getBytes("utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        if (b != null) {
            s = new BASE64Encoder().encode(b);
        }
        return s;
    }

    /**
     * 解密
     **/
    public static String fromBase64(String s) {
        if (s == null) {
            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;
    }


    /**
     * 网络图片转换Base64
     *
     * @param netImagePath netImagePath
     * @return java.lang.String
     * @author guowei
     * @date 2021/5/7
     */
    public static String netImageToBase64(String netImagePath) {
        String strNetImageToBase64 = null;
        final ByteArrayOutputStream data = new ByteArrayOutputStream();
        try {
            // 创建URL
            URL url = new URL(netImagePath);
            final byte[] by = new byte[1024];
            // 创建链接
            final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5000);

            try {
                InputStream is = conn.getInputStream();
                // 将内容读取内存中
                int len;
                while ((len = is.read(by)) != -1) {
                    data.write(by, 0, len);
                }
                // 对字节数组Base64编码
                BASE64Encoder encoder = new BASE64Encoder();
                strNetImageToBase64 = encoder.encode(data.toByteArray());
                // 关闭流
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                conn.disconnect();
            }
            return strNetImageToBase64;
        } catch (IOException e) {
            e.printStackTrace();
            return "error";
        }
    }


    /**
     * 本地图片转化成base64
     *
     * @param imgFilePath imgFilePath
     * @return java.lang.String
     * @author guowei
     * @date 2021/5/7
     */
    public static String getImageStr(String imgFilePath) {
        InputStream in = null;
        byte[] data = null;

        try {
            // 读取图片字节数组
            in = new FileInputStream(imgFilePath);

            data = new byte[in.available()];

            in.read(data);

            in.close();

        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }

        // 对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        // 返回Base64编码过的字节数组字符串
        return encoder.encode(data);

    }

    /**
     * base64字符串转化成图片 对字节数组字符串进行Base64解码并生成图片
     *
     * @param imgStr imgStr
     * @param path   path
     * @return boolean
     * @author guowei
     * @date 2021/5/7
     */
    public static boolean generateImage(String imgStr, String path) {
        // 图像数据为空
        if (imgStr == null) {
            return false;
        }

        BASE64Decoder decoder = new BASE64Decoder();

        try {
            // Base64解码
            byte[] b = decoder.decodeBuffer(imgStr);

            for (int i = 0; i < b.length; ++i) {
                // 调整异常数据
                if (b[i] < 0) {
                    b[i] += 256;
                }
            }

            // 生成jpeg图片

            OutputStream out = new FileOutputStream(path);

            out.write(b);
            out.flush();
            out.close();

            return true;

        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


    public static void main(String[] args) throws Exception {

        String url = "http://47.96.111.38:85/know/uploads/acupoint/a87f58d193f111e4be84565dcff86d38.gif";

        String path = "D:/0000.gif";

        //读取输入流,转换为Base64字符
        String str = netImageToBase64(url);

        System.out.println(str);

        //将Base64字符转换为图片
        generateImage(str, path);


    }
}
