package net.northking.cctp.designer.ws;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * base64与图片互转
 */
public class ImgBase64InstructUtil {

    private static String JPG = "jpg";
    private static String PNG = "png";

    private static final Logger logger = LoggerFactory.getLogger(ImgBase64InstructUtil.class);

    public static void main(String[] args) {


    }

    /**
     * base64转文件并输出到指定目录
     *
     * @param base64Str
     * @param fileName
     * @param filePath
     * @return
     */
    public static File decode(String base64Str, String fileName, String filePath) {
        File file = null;
        //创建文件目录
        File dir = new File(filePath);
        if (!dir.exists() && !dir.isDirectory()) {
            dir.mkdirs();
        }
        BufferedOutputStream bos = null;
        FileOutputStream fos = null;

        byte[] b = null;
        Base64.Decoder decoder = Base64.getDecoder();
        try {
            b = decoder.decode(replaceEnter(base64Str));
            file = new File(filePath + "/" + fileName);
            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            bos.write(b);
        } catch (IOException e) {
            logger.error("",e);
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    logger.error("",e);
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    logger.error("",e);
                }
            }
        }
        return file;
    }

    public static String replaceEnter(String str) {
        String reg = "[\n-\r]";
        Pattern p = Pattern.compile(reg);
        Matcher m = p.matcher(str);
        return m.replaceAll("");
    }



}

