package com.inspect.base.core.utils.file;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Arrays;

import org.apache.poi.util.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ImageUtils {
    private static final Logger log = LoggerFactory.getLogger(ImageUtils.class);

    public static byte[] getImage(String imagePath) {
        InputStream is = getFile(imagePath);

        Object object;
        try {
            byte[] byteArray = IOUtils.toByteArray(is);
            return byteArray;
        } catch (Exception e) {
            log.error("图片加载异常 {}", e);
            object = null;
        } finally {
            IOUtils.closeQuietly(is);
        }

        return (byte[]) object;
    }

    public static InputStream getFile(String imagePath) {
        try {
            byte[] result = readFile(imagePath);
            result = Arrays.copyOf(result, result.length);
            return new ByteArrayInputStream(result);
        } catch (Exception e) {
            log.error("获取图片异常 {}", e);
            return null;
        }
    }

    public static byte[] readFile(String url) {
        InputStream in = null;

        URLConnection urlConnection;
        try {
            URL urlObj = new URL(url);
            urlConnection = urlObj.openConnection();
            urlConnection.setConnectTimeout(30000);
            urlConnection.setReadTimeout('\uea60');
            urlConnection.setDoInput(true);
            in = urlConnection.getInputStream();
            return IOUtils.toByteArray(in);
        } catch (Exception e) {
            log.error("访问文件异常 {}", e);
            urlConnection = null;
        } finally {
            IOUtils.closeQuietly(in);
        }

        return urlConnection.toString().getBytes();
    }
}
