package com.xt.hb.data.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.StringUtils;

/**
 * 图片处理工具
 *
 * @author myhnuhai
 */
public class ImageUtil {
    private static Logger logger = LoggerFactory.getLogger(ImageUtil.class);

    /**
     * 从url下载文件
     * 
     * @param urlString
     * @param output
     */
    public static void download(String urlString, File output) {
        if (!StringUtils.hasText(urlString)) { return; }
        // 输入流
        InputStream is = null;
        try {
            // 构造URL
            URL url = new URL(urlString);
            // 打开连接
            URLConnection con = url.openConnection();
            is = con.getInputStream();
        }
        catch (IOException e) {
            logger.error("获取图片{}出错：{}", urlString, e.getMessage());
        }
        if (is == null) { return; }
        OutputStream os = null;
        try {
            os = new FileOutputStream(output);
            FileCopyUtils.copy(is, os);
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        finally {
            if (null != is) {
                try {
                    is.close();
                }
                catch (IOException e) {
                }
            }
            if (null != os) {
                try {
                    os.close();
                }
                catch (IOException e) {
                }
            }
        }
    }
}
