我正在尝试从url数组下载并保存所有图像,但问题是只有最后一个图像以名称img7.jpg保存。我不明白问题出在哪里?我想要下载并保存所有图像,名称为img1.jpg,img2.jpg,img3.jpg等。我需要在代码中哪些地方进行更改?
public class MainActivity extends ActionBarActivity {
ImageView imageView;
public static String[] stringArray = {"http://upload.wikimedia.org/wikipedia/en/9/90/Broken_Boundaries_of_Rohtas_Fort.jpg",
"http://upload.wikimedia.org/wikipedia/en/a/a0/Rohtas_View_4.jpg",
"http://upload.wikimedia.org/wikipedia/en/0/07/Rohtas_Fort_Gate.jpg",
"http://upload.wikimedia.org/wikipedia/en/7/78/Rohtas_Village_View_2nd.jpg",
"http://www.worldheritagesite.org/picx/w586.jpg",
"http://wpcontent.answcdn.com/wikipedia/en/thumb/6/68/Rani_Mahal_Rohtas_Fort_2.jpg/930px-Rani_Mahal_Rohtas_Fort_2.jpg",
"http://photos.wikimapia.org/p/00/01/75/75/69_big.jpg"};
int i = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView)findViewById(R.id.imageView1);
for (String url : stringArray){
Picasso.with(this)
.load(url)
.into(target);
i++;
}
}
private Target target = 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() +"/img"+i+".jpg");
try {
file.createNewFile();
FileOutputStream ostream = new FileOutputStream(file);
bitmap.compress(CompressFormat.JPEG, 75, ostream);
ostream.close();
}
catch (Exception e){
e.printStackTrace();
}
}
}).start();
}
@Override
public void onBitmapFailed(Drawable errorDrawable) {
}
@Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
if (placeHolderDrawable != null) {
}
}
};
}
答案 0 :(得分:1)
在你的情况下,毕加索异步加载你的图像。什么意思,
Picasso.with(this)
.load(url)
.into(target);
不会等到您的照片下载并存储到磁盘。因此,如果要保存图像,则计数器i
始终为(stringArray.length - 1)
。
做这样的事情:
...
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
int index = 0;
for (String url : stringArray) {
Picasso.with(this)
.load(url)
.into(new IndexTarget(index));
index++;
}
}
class IndexTarget implements Target {
private final int mIndex;
public IndexTarget(int index){
this.mIndex = index;
}
@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() +"/img"+mIndex+".jpg");
try {
file.createNewFile();
FileOutputStream ostream = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 75, ostream);
ostream.close();
}
catch (Exception e){
e.printStackTrace();
}
}
}).start();
}
@Override
public void onBitmapFailed(Drawable errorDrawable) {
}
@Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
}