volley获取网络图片,生成本地图片

本文介绍如何使用Volley在网络请求前检查本地缓存,若有缓存则直接使用并保存图片到本地;若无缓存,则进行网络请求并设置默认及错误图片资源。

使用volley获取网络图片前先检测是否有本地缓存,有缓存就读取缓存,并生成一个图片保存在本地指定位置(当然也可以访问网络的同时生成本地图片)。自定义一个CustomNetworkImageView继承NetworkImageView实现能够显示本地的Bitmap


RequestQueue mQueue = Volley.newRequestQueue(this);
		Cache cache = mQueue.getCache();
		Entry entry = cache.get(url);
		if (entry!=null) {
			try {
				// String data=new String(entry.data,"Utf-8");
				// 处理data,将其转化为JSON,XML,Bitmap等等
				Log.e(tag, "缓存存在");
				String string = Base64.encodeToString(entry.data,
						Base64.DEFAULT);
				huancunBitmap = convertStringToIcon(string);
				networkImageView.setLocalImageBitmap(huancunBitmap);
				// 把图片保存到本地指定文件夹
				byte[] byteIcon = Base64.decode(string, Base64.DEFAULT);
				for (int i = 0; i < byteIcon.length; ++i) {
					if (byteIcon[i] < 0) {
						byteIcon[i] += 256;
					}
				}
				// 建立一个文件对象
				File iconFile = new File(
						Environment.getExternalStorageDirectory(), "12345.png");
				FileOutputStream fos = new FileOutputStream(iconFile);
				if (!iconFile.exists()) {
					iconFile.createNewFile();
				}
				// 把图片数据写入文件形成图片
				fos.write(byteIcon);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			// 缓存中不存在,做网络请求
			Log.e(tag, "缓存不存在");
			imageLoader = new ImageLoader(mQueue, new ImageCache() {
			    @Override  
			    public void putBitmap(String url, Bitmap bitmap) {  
			    }  

			    @Override  
			    public Bitmap getBitmap(String url) {  
			        return null;  
			    }  
			});
			networkImageView.setDefaultImageResId(R.drawable.default_image);
			networkImageView.setErrorImageResId(R.drawable.failed_image);
			networkImageView.setImageUrl(url, imageLoader);
		}

我把代码上传了一份

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值