我有一个方法来加载图片,如果这张图片之前没有被加载过,它会从服务器上寻找。然后将其存储在应用程序的文件系统中。如果它已经在文件系统中存在,那么就从文件系统中加载该图像,因为这比从服务器获取要快得多。如果您之前加载过该图像而没有关闭应用程序,则将其存储在静态字典中,以便可以重新加载而不使用更多内存,以避免内存不足错误。
这一切都很好,直到我开始使用Picasso图像加载库。现在我正在将图像加载到ImageView中,但是我不知道如何获得返回的位图,以便我可以将其存储在文件或静态字典中。这让事情变得更加困难,因为它意味着每次它都会试图从服务器加载图像,这并不是我想要发生的事情。是否有一种方法可以在将其加载到ImageView中后获得位图?下面是我的代码:
public Drawable loadImageFromWebOperations(String url,
final String imagePath, ImageView theView, Picasso picasso) {
try {
if (Global.couponBitmaps.get(imagePath) != null) {
scaledHeight = Global.couponBitmaps.get(imagePath).getHeight();
return new BitmapDrawable(getResources(),
Global.couponBitmaps.get(imagePath));
}
File f = new File(getBaseContext().getFilesDir().getPath()
.toString()
+ "/" + imagePath + ".png");
if (f.exists()) {
picasso.load(f).into(theView);
下面这行是我尝试检索位图,但它抛出了一个空指针异常,我猜这是因为Picasso需要一段时间将图片添加到ImageView中。
Bitmap bitmap = ((BitmapDrawable)theView.getDrawable()).getBitmap();
Global.couponBitmaps.put(imagePath, bitmap);
return null;
} else {
picasso.load(url).into(theView);
return null;
}
} catch (OutOfMemoryError e) {
Log.d("Error", "Out of Memory Exception");
e.printStackTrace();
return getResources().getDrawable(R.drawable.default1);
} catch (NullPointerException e) {
Log.d("Error", "Null Pointer Exception");
e.printStackTrace();
return getResources().getDrawable(R.drawable.default1);
}
}
非常感谢您的帮助!