sha*_*her 10 android bitmap imageview picasso
我有一个加载图像的方法,如果图像尚未加载,它将在服务器上查找它.然后将其存储在apps文件系统中.如果它在文件系统中,则会加载该图像,因为这比从服务器中提取图像要快得多.如果您在未关闭应用程序之前加载了图像,它将存储在静态字典中,以便可以在不占用更多内存的情况下重新加载,以避免内存不足错误.
这一切都很好,直到我开始使用Picasso图像加载库.现在我将图像加载到ImageView中,但我不知道如何获取返回的Bitmap,以便我可以将其存储在文件或静态字典中.这使事情变得更加困难.因为这意味着它每次都试图从服务器加载图像,这是我不想发生的事情.有没有办法在将Bitmap加载到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);
Run Code Online (Sandbox Code Playgroud)
非常感谢任何帮助,谢谢!
jgu*_*net 41
使用Picasso,您不需要实现自己的静态字典,因为它是自动完成的.@intrepidkarthi是正确的,因为Picasso第一次加载时会自动缓存图像,因此它不会经常调用服务器来获取相同的图像.
话虽这么说,我发现自己处于类似的情况:我需要访问下载的位图,以便将其存储在应用程序的其他位置.为此,我稍微调整了@Gilad Haimov的答案:
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) {}
});
Run Code Online (Sandbox Code Playgroud)
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?) {}
})
Run Code Online (Sandbox Code Playgroud)
这使您可以访问加载的位图,同时仍然异步加载它.您只需记住在ImageView中设置它,因为它不再自动为您完成.
另外,如果您有兴趣了解图像的来源,可以使用相同的方法访问该信息.上述方法的第二个参数Picasso.LoadedFrom from是一个枚举,让你知道从位图是从(三个源加载的是什么来源DISK,MEMORY以及NETWORK(来源)方公司还提供了观看的可视化的方式,其中位图通过使用此处说明的调试指示符加载.
希望这可以帮助 !
毕加索让您直接控制下载的图像.要将下载的图像保存到文件中,请执行以下操作:
Picasso.with(this)
.load(currentUrl)
.into(saveFileTarget);
Run Code Online (Sandbox Code Playgroud)
哪里:
saveFileTarget = new Target() {
@Override
public void onBitmapLoaded (final Bitmap bitmap, Picasso.LoadedFrom from){
new Thread(new Runnable() {
@Override
public void run() {
File file = new File(Environment.getExternalStorageDirectory().getPath() + "/" + FILEPATH);
try {
file.createNewFile();
FileOutputStream ostream = new FileOutputStream(file);
bitmap.compress(CompressFormat.JPEG, 75, ostream);
ostream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
30861 次 |
| 最近记录: |