网络加载图片及图片缓存处理

来源:互联网 发布:淘宝登录itunes store 编辑:程序博客网 时间:2024/04/29 10:08

网络加载图片:

          1.(android使用)

                          InputStream is=new URL(String url).openStream();

                          Bitmap bm=BitmapFactory.decodeStream(is);

                          获得Bitmap对象后即可

          2.(java、android都可以)

             public static boolean downloadImg(String imgurl,String savedPath){
try {
URL url=new URL(imgurl);//获取URL对象
URLConnection conn=url.openConnection();//建立连接
InputStream is=conn.getInputStream();//获得输入流
File file=new File(savedPath);
FileOutputStream fos=new FileOutputStream(file);
int count;
while((count=is.read())!=-1){//读取数据
fos.write(count);
}
fos.close();
is.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
return true;
}

                        

缓存处理:

                 软引用SoftReference<T>,如果一个类型T的对象具有软引用,在内存空间足够时,垃圾回收器不会回收它,在内存空间不够时,垃圾回收器就会回收它

可以使用Map集合缓存具有软引用的对象,如Map<String ,SoftReference<Bitmap>> map=new HashMap<String,SoftReference<Bitmap>>();通过软引用对象的get方法即可获得Bitmap对象的强引用(SoftReference属于java提供的类)


LruCache是android提供的一个缓存工具类,其算法是最近最少使用算法,可以使GC体验更好,具体参考http://www.cnblogs.com/tianzhijiexian/p/4248677.html

                 


0 0
原创粉丝点击