package com.qmth.jkserver.util;

import com.qmth.jkserver.constant.SystemConstant;
import com.qmth.jkserver.signature.Constants;

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

/**
 * @Description: base64 util
 * @Param:
 * @return:
 * @Author: wangliang
 * @Date: 2020/12/16
 */
public class Base64Util implements Constants {

    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));
    }

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

    public static String audioToBase64(File file) {
        return "data:audio/mp3;base64," + encode(fileToByte(file));
    }

    /**
     * 文件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;
    }
}
