package com.yihu.jw.utils;

import sun.misc.BASE64Encoder;

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

/**
 * Created by Trick on 2019/12/12.
 */
public class ImgUtils {

    public static void main(String ag[]){
        try {
            String path ="http://ehr.yihu.com/fastdfs/group1/M00/00/1F/rBoAbl3V_yyAVdkaAAJwTja8N7I527.png";
            System.out.println(getImg(path));
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public static String getImg(String path)throws Exception{
        try{
            URL url = new URL(path);
            DataInputStream dataInputStream = new DataInputStream(url.openStream());
            return getBase64FromInputStream(dataInputStream);
        }catch (Exception e){
            e.printStackTrace();
        }
        return "";
    }

    private static String getBase64FromInputStream(InputStream is) throws Exception {
        // 将图片文件转化为字节数组字符串，并对其进行Base64编码处理
        byte[] data = null;
        // 读取图片字节数组
        try {
            ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
            byte[] buff = new byte[100];
            int rc = 0;
            while ((rc = is.read(buff, 0, 100)) > 0) {
                swapStream.write(buff, 0, rc);
            }
            data = swapStream.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    throw new Exception("输入流关闭异常");
                }
            }
        }
        //转化方法1
        BASE64Encoder encoder = new sun.misc.BASE64Encoder();
        return encoder.encodeBuffer(data).trim();
        //转化方法2
//        return new String(Base64.encodeBase64(data));
    }

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