我有一个加载图像的方法,如果图像在服务器上查找之前没有加载。然后将其存储在apps文件系统中。如果它在文件系统中,则加载该图像,因为这比从服务器中提取图像快得多。如果您在未关闭应用程序的情况下加载了图像,则图像将存储在静态字典中,以便在不占用更多内存的情况下重新加载,以避免出现内存不足错误。
在我开始使用毕加索图像加载库之前,一切都很好。现在我正在将图像加载到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);
**This line below was my attempt at retrieving the bitmap however
it threw a null pointer exception, I assume this is because it
takes a while for Picasso to add the image to the 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);
}
}
任何帮助都将不胜感激,谢谢!
最佳答案
对于毕加索,你不需要实现自己的静态字典,因为它是自动为你完成的。@IntrepidKarthi是正确的,因为图像在第一次加载时由毕加索自动缓存,因此它不会不断调用服务器来获取相同的图像。
这就是说,我发现自己也遇到了类似的情况:我需要访问下载的位图,以便将其存储在我的应用程序中的其他位置。为此,我调整了一下吉拉德·海莫夫的回答:
Java,Picasso的旧版本:
Picasso.with(this)
.load(url)
.into(new Target() {
@Override
public void onBitmapLoaded (final Bitmap bitmap, Picasso.LoadedFrom from) {
/* Save the bitmap or do something with it here */
// Set it in the ImageView
theView.setImageBitmap(bitmap);
}
@Override
public void onPrepareLoad(Drawable placeHolderDrawable) {}
@Override
public void onBitmapFailed(Drawable errorDrawable) {}
});
Kotlin,毕加索2.71828版:
Picasso.get()
.load(url)
.into(object : Target {
override fun onBitmapLoaded(bitmap: Bitmap, from: Picasso.LoadedFrom) {
/* Save the bitmap or do something with it here */
// Set it in the ImageView
theView.setImageBitmap(bitmap)
}
override fun onPrepareLoad(placeHolderDrawable: Drawable?) {}
override fun onBitmapFailed(e: Exception?, errorDrawable: Drawable?) {}
})
这使您可以在异步加载位图的同时访问加载的位图。您只需记住在imageview中设置它,因为它不再自动为您完成。
另一方面,如果你想知道你的图片来自哪里,你可以用同样的方法访问这些信息。上述方法的第二个参数
Picasso.LoadedFrom from
是一个枚举,它让您知道位图是从哪个源加载的(这三个源分别是DISK
、MEMORY
和NETWORK
。(Source)。square inc.还提供了一种可视化的方法,通过使用here说明的调试指示器来查看位图从何处加载。希望这有帮助!