package org.jeecg.module.custom.ocr.utils;

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

import java.io.*;
import java.net.URL;

/**
 * 转储图片工具类
 *
 * @author hugh(shuli.yao) 1397940314@qq.com
 * @version 1.0
 * @date 2024/3/16 18:37
 */
public class DownloadImgUtil {
    private static Logger logger = LoggerFactory.getLogger(DownloadImgUtil.class);

    /**
     * 下载网络图片缓存到本地服务器
     *
     * @param imageUrl
     * @param destinationFile
     */
    public static Boolean downloadImage(String imageUrl, String destinationFile) {
        //检查路径是否存在，不存在测进行新建
        if(destinationFile.lastIndexOf(File.separator)!=-1){
            String  directoryUrl = destinationFile.substring(0,destinationFile.lastIndexOf(File.separator));
            File file = new File(directoryUrl);
            if(!file.isDirectory()){
                file.mkdirs();
            }
        }

        try (InputStream in = new URL(imageUrl).openStream();
             FileOutputStream out = new FileOutputStream(destinationFile)) {

            byte[] buffer = new byte[4096];
            int n;
            while ((n = in.read(buffer)) != -1) {
                out.write(buffer, 0, n);
            }
            out.flush();
        } catch (Exception e) {
            logger.error("转储异常问题msg:{}",e.getMessage());
            logger.error("转储异常问题json:{}",e.getStackTrace());
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            e.printStackTrace(pw);
            String exceptionDetails = sw.toString();// 包含堆栈跟踪信息的字符串
            logger.error("图片本地化，转储图片异常:{}",exceptionDetails);

            return false;
        }
        return true;
    }


}
