首页 > 代码库 > 图片 缓存

图片 缓存

package cn.ibabyzone.library;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;


import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

//后台线程下载图片并写入SD卡函数
//如果本地图片存在则直接读取本地文件
public class AsyncImageLoader {

     private HashMap<String, SoftReference<Drawable>> imageCache;
     private static String SDPATH;
     private Activity thisActivity;
      
     public AsyncImageLoader(Activity thisActivity) {
             imageCache = new HashMap<String, SoftReference<Drawable>>();
             this.thisActivity = thisActivity;
         }
      
     public Drawable loadDrawable(final String imageUrl, final ImageCallback imageCallback) {
    	 	if (imageCache.containsKey(imageUrl)) {
                 SoftReference<Drawable> softReference = imageCache.get(imageUrl);
                 Drawable drawable = softReference.get();
                 if (drawable != null) {
                     return drawable;
                 }
             }
             final Handler handler = new Handler() {
                 public void handleMessage(Message message) {
                     imageCallback.imageLoaded((Drawable) message.obj, imageUrl);
                 }
             };
             new Thread() {
                 @Override
                 public void run() {
                     Drawable drawable = loadImageFromUrl(imageUrl,thisActivity);
                     imageCache.put(imageUrl, new SoftReference<Drawable>(drawable));
                     Message message = handler.obtainMessage(0, drawable);
                     handler.sendMessage(message);
                 }
             }.start();
             return null;
         }
     
     
    //判断本地文件是否存在存在则读取本地 不存在则下载
    //返回数据为图片数据
    public static Drawable loadImageFromUrl(String url,Activity thisActivity) {
    	URL m;
    	if(android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
		{
			SDPATH = Environment.getExternalStorageDirectory() + "/";
			
		}
		else
		{
			SDPATH= thisActivity.getFilesDir().toString() + "/";
		}
    	InputStream i = null;
        InputStream j = null;
    	int urlt = url.lastIndexOf("/");
		String imgename = url.substring(urlt+1,url.length()-4);
		FileUtils temp =new FileUtils(thisActivity);
		String file =  "album/"+imgename;
		Drawable d=null;
    	if(temp.isFileExist(file))
    	{
    		i =readimage(imgename,thisActivity);
    		d = Drawable.createFromStream(i, "src");
    	}
    	else
    	{
    		//if(!temp.isFileExist(file+".temp"))
    		//{
	            try {
	            	FileUtils images = new FileUtils(thisActivity);
	            	//Log.e("a",imgename);
	            	images.creatSDFile("album/"+imgename+".temp");
	            	m = new URL(url);
	            	i = (InputStream) m.getContent();            	
	            	byte[] swapStream ;
	            	swapStream=readStream(i);
	            	InputStream is = new ByteArrayInputStream(swapStream);
	            	d = Drawable.createFromStream(is, "src");
	            	
	            	is = new ByteArrayInputStream(swapStream);
	            	
	            	images.write2SDFromInput("album/", imgename+".temp", is);
		            //File files =new File(SDPATH+"yqq/album/"+ imgename+".temp");
		            //File nfile = new File(SDPATH+"yqq/album/"+imgename);
					//files.renameTo(nfile);
					moveFile(SDPATH+"yqq/album/"+ imgename+".temp",SDPATH+"yqq/album/"+imgename);
	            } catch (MalformedURLException e1) {
	                e1.printStackTrace();
	            } catch (IOException e) {
	                e.printStackTrace();
	            } catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
    		//}
    	}		
            return d;
    }
    public static byte[] readStream(InputStream inStream) throws Exception{
    	ByteArrayOutputStream outStream = new ByteArrayOutputStream();
    	byte[] buffer = new byte[1024];
    	  int len = 0;
    	  while( (len=inStream.read(buffer)) != -1){
    	   outStream.write(buffer, 0, len);
    	  }
    	  outStream.close();
    	  inStream.close();
    	  return outStream.toByteArray();
    }
 
    //从本地SD卡中读取已有的图片
    public static FileInputStream readimage(String name,Activity thisActivity)
    {
    	InputStream temp;
    	if(android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
		{
			SDPATH = Environment.getExternalStorageDirectory() + "/yqq/";
			
		}
		else
		{
			SDPATH= thisActivity.getFilesDir().toString() + "/yqq/";
		}
    	File file = new File(SDPATH +"album/"+ name);   
    	FileInputStream fis = null;
		try {
			fis = new FileInputStream(file);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}   
    	return fis;   

    }
    
    public static boolean moveFile(String srcFileName, String destDirName) {  
		File srcFile = new File(srcFileName);  
		if(!srcFile.exists() || !srcFile.isFile())
			return false;
		try {   
	           int bytesum = 0;   
	           int byteread = 0;   
	           File oldfile = new File(srcFileName);   
	           if (oldfile.exists()) { //文件存在时    
	               InputStream inStream = new FileInputStream(srcFileName); //读入原文件    
	               FileOutputStream fs = new FileOutputStream(destDirName);   
	               byte[] buffer = new byte[1444];   
	               int length;   
	               while ( (byteread = inStream.read(buffer)) != -1) {   
	                   bytesum += byteread; //字节数 文件大小    
	                   System.out.println(bytesum);   
	                   fs.write(buffer, 0, byteread);   
	               }   
	               inStream.close();   
	           }   
	       }   
	       catch (Exception e) {   
	    	   return false;
	  
	       } 
		return true;  
	}
    
    //类接口  
    public interface ImageCallback {
             public void imageLoaded(Drawable imageDrawable, String imageUrl);
         }

}

使用示例:


Drawable cachedImage = asyncImageLoader.loadDrawable(url,
                        new ImageCallback() {
                            public void imageLoaded(Drawable imageDrawable,
                                    String imageUrl) {
                                if (imageDrawable != null) {
                                    adv_image.setImageDrawable(imageDrawable);

                                    int screenWidth = getWindowManager()
                                            .getDefaultDisplay().getWidth();
                                    double bl = (double) imageDrawable
                                            .getMinimumHeight()
                                            / imageDrawable.getMinimumWidth();
                                    int height = (int) (screenWidth * bl);
                                    adv_image
                                            .setLayoutParams(new RelativeLayout.LayoutParams(
                                                    RelativeLayout.LayoutParams.MATCH_PARENT,
                                                    height));
                                    ;
                                    waiting_bar.setVisibility(View.GONE);
                                }
                                // imageViewByTag.setImageDrawable(imageDrawable);
                            }
                        });
                if (cachedImage != null) {
                    adv_image.setImageDrawable(cachedImage);
                    waiting_bar.setVisibility(View.GONE);
                    int screenWidth = getWindowManager().getDefaultDisplay()
                            .getWidth();
                    double bl = (double) cachedImage.getMinimumHeight()
                            / cachedImage.getMinimumWidth();
                    int height = (int) (screenWidth * bl);
                    adv_image.setLayoutParams(new RelativeLayout.LayoutParams(
                            RelativeLayout.LayoutParams.MATCH_PARENT, height));
                }
            } else {
                // adv_image.setImageResource(R.drawable.no_pic);
                waiting_bar.setVisibility(View.GONE);
            }




图片 缓存