package com.younike.common.utils.image;

import sun.misc.BASE64Encoder;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Base64;
import java.util.Objects;

public class ImageToBase64 {

private static String strNetImageToBase64;

    public static void main(String[] args) {
        //第一个:把网络图片装换成Base64
        String netImagePath = "http://fresh-life.oss-cn-shanghai.aliyuncs.com/faceimages/2021/10/27/1635316258281.jpg";
        //下面是网络图片转换Base64的方法
        String s = NetImageToBase64(netImagePath);
        System.out.println(s);
        //下面是本地图片转换Base64的方法
//        String imagePath = "本地图片路径";
//        ImageToBase64(imagePath);
    }

    /**
     * 网络图片转换Base64的方法
     *
     * @param netImagePath
     */
    public static String NetImageToBase64(String netImagePath) {
        ByteArrayOutputStream outPut = new ByteArrayOutputStream();
        byte[] data = new byte[1024];
        try {
            // 创建URL
            URL url = new URL(netImagePath);
            // 创建链接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(10 * 1000);

            if(conn.getResponseCode() != 200) {
                return "fail";//连接失败/链接失效/图片不存在
            }
            InputStream inStream = conn.getInputStream();
            int len = -1;
            while ((len = inStream.read(data)) != -1) {
                outPut.write(data, 0, len);
            }
            inStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 对字节数组Base64编码
        byte[] encode = Base64.getEncoder().encode(outPut.toByteArray());
        String res = new String(encode);
        return res;
    }


    /**
     * 本地图片转换Base64的方法
     *
     * @param imgPath
     */

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






}
