---
title: "网络获取图片的方法的重写--较简洁(如果手机缓存里面有就从缓存获取)"
author: "学而乐"
date: "2011-06-10T11:54:04Z"
tags: ["Android", "Blog", "ITeye"]
categories: ["移动开发"]
slug: "untitled"
draft: false
lastmod: "2011-06-10T11:54:04Z"
id: 1075196
url: "https://doinone.iteye.com/blog/1075196"
---

我前面的博客写了网络获取图片的方法（见：[《Android中获取网络图片的方法(如果手机缓存里面有就从缓存获取)》](http://doinone.iteye.com/blog/1074366)），但比较原始，代码比较冗长，想简化一下。另外一篇文章：[《Android中获取网络图片的三种方法》](http://doinone.iteye.com/blog/1074283)里面的公用获取Drawable对象的方法，是不会缓存到手机里面的，这里就把那个方法（loadImageFromNetwork() ）重写一下,达到图片缓存的目的：


```java
// 如果缓存里面有就从缓存获取，否则网络获取图片，返回Drawable对象
	public static Drawable loadImageFromNetwork(Context context, String imageUrl)
	{
		Drawable drawable = null;
		if(imageUrl == null )
			return null;
		String imagePath = "";
		String   fileName   = "";
			
		// 获取url中图片的文件名与后缀
		if(imageUrl!=null&&imageUrl.length()!=0){ 
            fileName  = imageUrl.substring(imageUrl.lastIndexOf("/")+1);
		}
		
		// 图片在手机本地的存放路径,注意：fileName为空的情况
		imagePath = context.getCacheDir() + "/" + fileName;

		Log.i("test","imagePath = " + imagePath);
		File file = new File(context.getCacheDir(),fileName);// 保存文件
		Log.i("test","file.toString()=" + file.toString());
		if(!file.exists()&&!file.isDirectory())
		{
			try {
				// 可以在这里通过文件名来判断，是否本地有此图片
				
				FileOutputStream   fos=new   FileOutputStream( file );
				InputStream is = new URL(imageUrl).openStream();
				int   data = is.read(); 
				while(data!=-1){ 
				        fos.write(data); 
				        data=is.read();; 
				} 
				fos.close();
				is.close();
//				drawable = Drawable.createFromStream(
//						new URL(imageUrl).openStream(), file.toString() ); // (InputStream) new URL(imageUrl).getContent();
				drawable = Drawable.createFromPath(file.toString());
				Log.i("test", "file.exists()不文件存在，网上下载:" + drawable.toString());
			} catch (IOException e) {
				Log.d("test", e.getMessage());
			}
		}else
		{
			drawable = Drawable.createFromPath(file.toString());
			Log.i("test", "file.exists()文件存在，本地获取");
		}
		
		if (drawable == null) {
			Log.d("test", "null drawable");
		} else {
			Log.d("test", "not null drawable");
		}
		
		return drawable ;
	}
```