package shop.alien.util.byteutil;

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

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;

/**
 * 二进制数组转文件
 *
 * @author ssk
 * @version 1.0
 * @date 2020/5/9 10:01
 */
public class ByteToFileUtil {

    /**
     * logger
     */
    private static final Logger logger = LoggerFactory.getLogger(ByteToFileUtil.class);

    /**
     * 二进制数组转图片
     *
     * @param bytes    二进制数组
     * @param filePath 文件路径
     * @param fileName 文件名
     * @throws IOException IOException
     */
    public static String byteToImage(byte[] bytes, String filePath, String fileName) throws IOException {
        //文件路径+文件名+文件格式
        String pathName = filePath + File.separator + fileName + ".jpg";
        logger.info("ByteToFileUtil/byteToImage/pathName={}", pathName);
        File path = new File(filePath);
        if (!path.exists()) {
            path.mkdirs();
        }
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
        BufferedImage bufferedImage = ImageIO.read(byteArrayInputStream);
        try {
            //可以是jpg,png,gif格式
            File file = new File(pathName);
            ImageIO.write(bufferedImage, "jpg", file);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            logger.info("导出成功,文件路径:{}", pathName);
            byteArrayInputStream.close();
        }
        return pathName;
    }
}
