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

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 に答える