0

所以我试图调整我使用这种方法下载的图像的大小,但是,在调整了大约 100 张图像的大小后,程序变得非常慢。我认为这是因为我忘记关闭连接或其他东西,但我很确定我关闭了所有流和连接。我不知道出了什么问题,什么堵塞了我所有的记忆,使它运行得如此缓慢,以至于最终程序只是暂停了。请帮忙!

private String resizePhoto(String str, String leg_id, int size, String path) {
    HttpURLConnection connection = null;
    if (str == null || str.trim().equals(""))
        return "http://s3.amazonaws.com/37assets/svn/765-default-avatar.png";
    try {
        URL url = new URL(str);
        connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        InputStream stream = url.openStream();
        BufferedImage img = ImageIO.read(stream);
        BufferedImage newImg = Scalr.resize(img, Mode.FIT_TO_WIDTH, size, Scalr.OP_ANTIALIAS);

        Iterator<ImageWriter> writerIt = ImageIO.getImageWritersByFormatName("jpeg");
        if (writerIt.hasNext() ) {
            ImageWriter writer = writerIt.next();
            FileOutputStream f = new FileOutputStream(path + leg_id + ".jpg");
            ImageOutputStream ios = ImageIO.createImageOutputStream(f);
            writer.setOutput(ios);
            ImageWriteParam writeParam = writer.getDefaultWriteParam();
            writeParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
            writeParam.setCompressionQuality(0.9f);
            writer.write(null, new IIOImage(newImg, null, null), writeParam);
            f.close();
            writer.dispose();
            ios.close();
        }

       stream.close();
       connection.disconnect();
       return path + leg_id + ".jpg";

    } catch (MalformedURLException e) {e.printStackTrace();System.exit(0);
    } catch (IOException e) {};

    return "http://s3.amazonaws.com/37assets/svn/765-default-avatar.png";
}
4

2 回答 2

0

当然,您可能没有使用该代码清理所有资源。您在IOExceptions没有任何消息的情况下吞咽,因此您将无法轻松查看是否发生了这种情况。我建议在你的上使用一个finally块,try-catch并在其中包含你的.close(),.disconnect().dispose()调用。确保首先检查它们是否为 null 以防止 NPE。

于 2013-06-26T22:13:15.237 回答
0

您应该将所有close()方法放入 finally 块中,以便在抛出异常时它们仍然关闭。例如

//Declare stream as null
FileOutputStream f = null
try
{ 
   //initialise stream
   f = new FileOutputStream(path + leg_id + ".jpg");
   // do your stuff
}
catch (//the exceptions you want to catch)
{
    //What ever you want to do with caught exceptions, you should always at least print statcktrace
    e.printStackTrace();
}
finally
{
    if(f!= null)
        f.close();  // this might need its own try/catch also
}

目前在您的代码中,您可能会遇到 IO 异常,而您只需忽略它

于 2013-06-26T22:15:17.523 回答