ImageIO.read()引发的线程阻塞

/ 后端 / 没有评论 / 653浏览

问题:

ImageIO.read()一般用于读取输入流,file或者直接读取网络图片;

(1)ImageIO.read(file) (2)ImageIO.read(inputStream) (3)ImageIO.read(new Url(""))

存在的问题

1.根据注释说明,其不会关闭相关流; 2.没有超时处理,会一直阻塞;

该方法注释说明,其不会关闭流:

使用从当前注册的URL中自动选择的ImageReader解码提供的URL,返回BufferedImage。一个InputStream从URL中获取,它被包装在一个ImageInputStream中。如果没有注册的ImageReader声称能够读取结果流,则返回null。 getusecache和getCacheDirectory的当前缓存设置将用于控制ImageInputStream中创建的缓存。 这个方法不尝试定位可以直接从URL读取的imagereader;这可以使用iiregistry和ImageReaderSpi完成。 参数: input -一个要读取的URL。 返回: 包含已解码输入内容的BufferedImage,或为空。 抛出: IllegalArgumentException -如果输入为空。 IOException -如果在读取过程中发生错误。

解决

public class ImageIOUtils {

    public static BufferedImage read(String urlStr) {
        HttpURLConnection connection = null;
        InputStream inputStream = null;
        try {
            URL url = new URL(urlStr);
            connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setReadTimeout(3000);
            connection.setConnectTimeout(2000);
            inputStream = connection.getInputStream();
            return ImageIO.read(inputStream);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }


    public static BufferedImage read(URL url) {
        HttpURLConnection connection = null;
        InputStream inputStream = null;
        try {
            connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setReadTimeout(3000);
            connection.setConnectTimeout(2000);
            inputStream = connection.getInputStream();
            return ImageIO.read(inputStream);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    public static BufferedImage read(InputStream inputStream) {
        try {
            return ImageIO.read(inputStream);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }
}