package com.qmth.paper.library.common.util;

import com.qmth.paper.library.common.contant.SystemConstant;

import java.io.File;
import java.io.FileInputStream;
import java.util.Base64;

public class Base64Util {

    public static String encode(byte[] input) {
        return new String(Base64.getEncoder().encode(input), SystemConstant.CHARSET);
    }

    public static byte[] decode(String input) {
        return Base64.getDecoder().decode(input.getBytes(SystemConstant.CHARSET));
    }

    public static String imageToBase64(String path) {
        File file = new File(path);
        return imageToBase64(file);
    }

    /**
     * 文件File类型转BASE64
     *
     * @param file
     * @return
     */
    public static String imageToBase64(File file) {
        return "data:image/png;base64," + encode(fileToByte(file));
    }

    public static String stringToBase64(String base64String) {
        return "data:image/png;base64," + base64String;
    }

    /**
     * 文件File类型转byte[]
     *
     * @param file
     * @return
     */
    private static byte[] fileToByte(File file) {
        byte[] fileBytes = null;
        FileInputStream fis;
        try {
            fis = new FileInputStream(file);
            fileBytes = new byte[(int) file.length()];
            fis.read(fileBytes);
            fis.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return fileBytes;
    }
}
