我是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