package com.yx.face.boot.uitls;

import sun.misc.BASE64Encoder;

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

/**
 * @ClassName DownLoad
 * @Description
 * @Author xrf
 * @Date 2021/12/2 15:52
 */
public class DownLoad {
    private static void downloadPicture(String urlList,String path) {
        try {
            URL url = new URL(urlList);
            DataInputStream dataInputStream = new DataInputStream(url.openStream());
            FileOutputStream fileOutputStream = new FileOutputStream(new File(path));
            ByteArrayOutputStream output = new ByteArrayOutputStream();

            byte[] buffer = new byte[1024];
            int length;

            while ((length = dataInputStream.read(buffer)) > 0) {
                output.write(buffer, 0, length);
            }
            fileOutputStream.write(output.toByteArray());
            dataInputStream.close();
            fileOutputStream.close();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * url转Base63
     * @param url
     * @return
     */
    public static String tranUrlToBase64String(String url){
        try {
            URL urlImg = new URL(url);
            HttpURLConnection httpURLConnection = (HttpURLConnection) urlImg.openConnection();
            httpURLConnection.addRequestProperty("User-Agent","Mozilla / 4.76");
            InputStream is = httpURLConnection.getInputStream();
            //定义字节数组大小；
            byte[] buffer = new byte[1024];
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            int rc =0 ;
            while((rc = is.read(buffer,0,100))>0){
                byteArrayOutputStream.write(buffer,0,rc);
            }
            buffer = byteArrayOutputStream.toByteArray();
            BASE64Encoder encoder = new BASE64Encoder();
            return encoder.encode(buffer);

        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

//    public static void main(String[] args) throws IOException {
//        String s = tranUrlToBase64String("https://ldb-airport.hz-hanghui.com:9100/data/hanghui/16375779864021cec7bf9ad7f4685973b4da438faf08a.png");
//
//        Base64Util.GenerateImage(s,"d:/8.jpg");
//    }
}

