我是Android新手。 我正在從ListView中下載Internet中的圖像。我在文件對象中獲取url,但是當我將它發送到Bitmap對象時,位圖對象返回null意味着圖像不會加載到位圖object.please回覆我。代碼在這裏:如何從文件中獲取url到位圖對象中
private Bitmap getBitmap(String url) {
String filename = String.valueOf(url.hashCode());
File f = new File(cacheDir, filename);
// here in f i getting image url
// here in bitmap the url is not loaded & get null
Bitmap bitmap = BitmapFactory.decodeFile(f.getPath());
if(bitmap != null) return bitmap;
// Nope, have to download it
try {
bitmap =
BitmapFactory.decodeStream(new URL(url).openConnection().getInputStream());
// save bitmap to cache for later
writeFile(bitmap, f);
return bitmap;
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
private void writeFile(Bitmap bmp, File f) {
FileOutputStream out = null;
try {
out = new FileOutputStream(f);
bmp.compress(Bitmap.CompressFormat.PNG, 80, out);
} catch (Exception e) {
e.printStackTrace();
}
finally {
try { if (out != null) out.close(); }
catch(Exception ex) {}
}
}
你想下載一個html頁面保存爲PNG圖片?或者URL指向一個png已經? – nurxyz