最近做项目,要下载图片到本地(不是指缓存),之前用过HttpURLConnection和HttpCLient,但是感觉太繁琐,而且6.0之后到Apache包也不支持了,后来我想到了Picasso的缓存,Picasso缓存图片,那肯定是下载到本地实现了,我们只要更改下本地路径,就能轻松实现了。
废话不多说,直接上代码了。
private void download() {
String url = mList.get(mPosition);
Target target = new Target(){
@Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
String imageName = System.currentTimeMillis() + ".png";
File dcimFile = FileUtil
.getDCIMFile(FileUtil.PATH_PHOTOGRAPH,imageName);
LogCat.i("bitmap="+bitmap);
FileOutputStream ostream = null;
try {
ostream = new FileOutputStream(dcimFile);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, ostream);
ostream.close();
} catch (Exception e) {
e.printStackTrace();
}
Toast.makeText(PicActivity.this,"图片下载至:"+dcimFile,Toast.LENGTH_SHORT).show();
}
@Override
public void onBitmapFailed(Drawable errorDrawable) {
}
@Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
};
Picasso.with(this).load(url).into(target);
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
这样就轻松实现了,值得注意的是,我们经常用的是into(ImageView target),其实into还能传入很多不同的对象。今天有点晚了,先写到这,关于Picasso,还是有很多技巧可以探索的。之前还写过一篇Android 使用Picasso加载网络图片等比例缩放的文章,也欢迎大家有空去指点一下。
参考文献:
http://stackoverflow.com/questions/27729976/download-and-save-images-using-picasso