gpt4 book ai didi

android - 使用 Picasso 下载多张图片

转载 作者:行者123 更新时间:2023-11-29 19:25:46 26 4
gpt4 key购买 nike

我正在尝试使用 picasso 下载多张图片。这是我的代码:

for(int i=1; i <=20; i++){
String url = img_url + i + "/profile.jpg";
String img_dir = img_dir + i;
Picasso.with(this).load(url).into(picassoImageTarget(getApplicationContext(),img_dir, img_name));

}

该站点的 URL 如下所示:

site.com/img/equipment/1/profile.jpg, 
site.com/img/equipment/2/profile.jpg,
site.com/img/equipment/3/profile.jpg

等等...

我试过了

Picasso.with(this).load(url).into(picassoImageTarget(getApplicationContext(),img_dir, img_name));

没有 for 循环,它正在工作。当我将它放在循环中时,图像不会下载。

这是我的目标

private Target picassoImageTarget(Context context, final String imageDir, final String imageName) {
Log.d("picassoImageTarget", " picassoImageTarget");
ContextWrapper cw = new ContextWrapper(context);
final File directory = cw.getDir(imageDir, Context.MODE_PRIVATE); // path to /data/data/yourapp/app_imageDir
return new Target() {
@Override
public void onBitmapLoaded(final Bitmap bitmap, Picasso.LoadedFrom from) {
new Thread(new Runnable() {
@Override
public void run() {
final File myImageFile = new File(directory, imageName); // Create image file
FileOutputStream fos = null;
try {
fos = new FileOutputStream(myImageFile);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Log.i("image", "image saved to >>>" + myImageFile.getAbsolutePath());

}
}).start();
}

@Override
public void onBitmapFailed(Drawable errorDrawable) {
}
@Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
if (placeHolderDrawable != null) {}
}
};
}

请帮忙。谢谢。

最佳答案

Targets are held in WeakReferences.

您需要保留对要保留的目标的引用,以防止它们被垃圾回收。

也许你的代码看起来像这样:

final class MyLoader {
final ArrayList<Target> targets = new ArrayList<>(20);
void load(...) {
for(...) {
Target target = picassoImageTarget(...);
targets.add(target);
picasso.load(...).into(target); // TODO: Maybe remove from list when complete.
}
}
}

关于android - 使用 Picasso 下载多张图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41461162/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com