java似乎没有正确下载图像

时间:2015-03-01 14:45:07

标签: java image download

经过一些研究后,我找到了下载图像并将其存储到文件中的最简单方法。

到目前为止,这是我的代码:

    public boolean descargarArchivo(String url, String outputDirectory) {
    try {
        File img = new File(outputDirectory); 
        URLConnection conn = new URL(url).openConnection();
        conn.connect();
        try (InputStream in = conn.getInputStream(); 
             OutputStream out = new FileOutputStream(img)) {
            int b = 0;
            while (b != -1) {
                b = in.read();
                if (b != -1) {
                    out.write(b); 
                }
            } 
        }
        return true;
    } catch (IOException ioe) {
        ioe.printStackTrace();
    }
    return false;
} 

此代码存在的问题是有时执行错误的图片下载。让我用一个例子来澄清这个想法:

Original Image enter image description here

虽然第一张图片是原始图片(并且输出文件应该是这样的),但第二张图片是图片的真实输出文件,由该代码执行,这显然是错误的(忽略分辨率,I& #39;我只是谈论这个"错误的像素")。有没有办法改善这个?我应该改变从网上下载图片的方式吗?

1 个答案:

答案 0 :(得分:0)

这就是我从网址读取图片的方式:

try {
        final InputStream inputStream = createInputStream(new URL(getImgUrl()));
        try {
               return ImageIO.read(inputStream);
        } finally {
               inputStream.close();
        }
 } catch (MalformedURLException e) {
        e.printStackTrace();
 } catch (SocketTimeoutException e) {
        //e.printStackTrace();          in case of error, will try again
 } catch (IOException e) {
        e.printStackTrace();
 }
使用

protected InputStream createInputStream(URL url) throws IOException {
    URLConnection con = url.openConnection();
    con.setConnectTimeout(500);
    con.setReadTimeout(200);
    return con.getInputStream();
}
相关问题