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

来源:互联网 发布:图解希尔巴布尔美灭mac 编辑:程序博客网 时间:2024/04/30 09:32

使用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);}

我把代码上传了一份

0 0
原创粉丝点击