package com.tykj.dev.device.zxing.util;

import javax.imageio.stream.FileImageOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Base64;

/**
 * DATE:2021-7-21
 * Author:zsp
 */
public class Base64Util {


    /**
     * 转换成base64
     * @param imgFile
     * @return
     */
    public static String getImageStr(String imgFile) {
        InputStream inputStream = null;
        byte[] data = null;
        try {
            inputStream = new FileInputStream(imgFile);
            data = new byte[inputStream.available()];
            inputStream.read(data);
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 加密
        Base64.Encoder encoder = Base64.getEncoder();
        return encoder.encodeToString(data);
    }

    /**
     * 转换成字节数组
     * @param path
     * @return
     */
    public static byte[] getFileBytes(String path) {
        ArrayList bytesList = new ArrayList();
        byte[] bytes = new byte[1];
        FileInputStream inStream = null;
        try {
            inStream = new FileInputStream(path);
            while (inStream.read(bytes) > 0) {
                bytesList.add(bytes[0]);
            }
            bytes = new byte[bytesList.size()];
            for (int i = 0; i < bytes.length; i++) {
                bytes[i] = (byte) bytesList.get(i);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (inStream != null) {
                    inStream.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return bytes;
    }

    /**
     * 将字节转换成图片
     * @param data
     * @param path
     */
    public static void byte2image(byte[] data, String path) {
        if (data.length < 3 || path.equals("")) {
            return;
        }
        try {
            FileImageOutputStream imageOutput = new FileImageOutputStream(new File(path));
            imageOutput.write(data, 0, data.length);
            imageOutput.close();
            System.out.println("Make Picture success,Please find image in " + path);
        }
        catch (Exception ex) {
            System.out.println("Exception: " + ex);
            ex.printStackTrace();
        }
    }
}
