我想从网址列表中下载一些图片。这就是我的工作方式:
public void setLocalPhotosUrl() throws IOException {
int size;
if(attachments.size()<3)
size=attachments.size();
else
size=3;
for(int i=0;i<size;++i){
String filename =title.replace(" ","")+i+".jpg";
File destination = new File(Corale.getPhotos(),filename);
URL photoUrl = new URL(attachments.get(i).getUrl());
InputStream is = photoUrl.openStream();
OutputStream os = new FileOutputStream(destination);
byte[] b = new byte[2048];
int length;
while ((length = is.read(b)) != -1) {
os.write(b, 0, length);
}
is.close();
os.close();
if(checkIfValid(destination))
localPhotosUrl.add(destination.getAbsolutePath());
else
i--;
}
}
但事实证明,有很多照片,占用的空间达到270MB,我如何压缩图像然后将其保存到手机SD?
答案 0 :(得分:0)
试试这个
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/saved_images");
myDir.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "Image-"+ n +".jpg";
File file = new File (myDir, fname);
if (file.exists ()) file.delete ();
try {
FileOutputStream out = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
并在清单
中添加此内容<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />