所以我试图调整我使用这种方法下载的图像的大小,但是,在调整了大约 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";
}