首页 > 代码库 > Android图片异步加载

Android图片异步加载

获取图片工具类:

public class ApacheUtility {

/**
  * 获取图片流
  * 
  * @param uri 图片地址

  * @return
  * @throws MalformedURLException
  */
 public static InputStream GetImageByUrl(String uri) throws MalformedURLException {
  URL url = new URL(uri);
  URLConnection conn;
  InputStream is;
  try {
   conn = url.openConnection();
   conn.connect();
   is = conn.getInputStream();

   // 或者用如下方法

   // is=(InputStream)url.getContent();
   return is;
  } catch (IOException e) {
   e.printStackTrace();
  }

  return null;
 }

 

 

/**
  * 获取Bitmap

  * 
  * @param uri 图片地址
  * @return
  */
 public static Bitmap GetBitmapByUrl(String uri) {

  Bitmap bitmap;  
  InputStream is;
  try {

   is =  GetImageByUrl(uri); 

   bitmap = BitmapFactory.decodeStream(is);
   is.close();

   return bitmap;

  } catch (MalformedURLException e) {
   e.printStackTrace();

  } catch (IOException e) {
   e.printStackTrace();
  }

  return null;
 }

 

 

/**
  * 获取Drawable

  * 
  * @param uri  图片地址

  * @return
  */
 public static Drawable GetDrawableByUrl(String uri) {

  Drawable drawable;  
  InputStream is;
  try {

   is =  GetImageByUrl(uri); 

   drawable= Drawable.createFromStream(is, "src");

   is.close();

   return drawable;

  } catch (MalformedURLException e) {
   e.printStackTrace();

  } catch (IOException e) {
   e.printStackTrace();
  }

  return null;
 }

}

 

异步任务加载图片类:

/**
  * 异步加载图片
  * 

  */
 public class LoadImageAsyncTask extends AsyncTask<String, Integer, Bitmap> {
  private ImageView imageView;

  @Override
  protected void onPostExecute(Bitmap bitmap) {
   if (null != imageView) {
    imageView.setImageBitmap(bitmap);
   }
  }
  
  // 设置图片视图实例
  public void setImageView(ImageView image) {
   this.imageView = image;
  }

  @Override
  protected Bitmap doInBackground(String... params) {
   Bitmap bitmap = ApacheUtility.GetBitmapByUrl(params[0]); // 调用前面 ApacheUtility 类的方法

   return bitmap;
  }
 }

调用过程如下:

String imgUrl="http://www.streetcar.org/mim/cable/images/cable-01.jpg"; // 图片路径

LoadImageAsyncTask task = new LoadImageAsyncTask();

task.setImageView(iv); // iv为获取的ImageView对象实例

tast.execute(imgUrl); // 执行任务,参数与 doInBackground(String... params) 方法参数一致

 

异步图片加载类:

参考文章:http://blog.163.com/guozioo@126/blog/static/64086947201136102838503/

 

public class AsyncImageLoader {

 // SoftReference是软引用,是为了更好的为了系统回收变量
 private HashMap<String, SoftReference<Drawable>> imagesCache;

 public AsyncImageLoader() {
   imagesCache = new HashMap<String, SoftReference<Drawable>>();
 }
 
 public Drawable loadDrawable(final String imageUrl,final ImageView imageView,final ILoadImageCallback callback){
   if(imagesCache.containsKey(imageUrl)){
     // 从缓存中获取
     SoftReference<Drawable> softReference=imagesCache.get(imageUrl);
     Drawable drawable=softReference.get();
     if(null!=drawable){
       return drawable;
     }
  }
  
  final Handler handler=new Handler(){
    public void handleMessage(Message message){
      callback.onObtainDrawable((Drawable)message.obj, imageView);
    }
  };
  //建立一个新的线程下载图片
  new Thread(){
    public void run(){
      Drawable drawable=ApacheUtility.GetBitmapByUrl(imageUrl); // 调用前面 ApacheUtility 类的方法

      imagesCache.put(imageUrl, new SoftReference<Drawable>(drawable));
      Message msg=handler.obtainMessage(0, drawable);
      handler.sendMessage(msg);
    }
  }.start();
   
  return null;
 }

 

 /**
  * 异步加载图片的回调接口

  */
 public interface ILoadImageCallback {
  public void onObtainDrawable (Drawable drawable, ImageView imageView);
 }
}

调用过程如下:

String imgUrl="http://www.streetcar.org/mim/cable/images/cable-01.jpg"; // 图片路径

AsyncImageLoader  imagLoader = new AsyncImageLoader();

Drawable cachedImage= imagLoader.loadDrawable(imgUrl,iv,new ILoadImageCallback(){

  public void onObtainDrawable (Drawable drawable, ImageView imageView){

    imageView.setImageDrawable(drawable);

  }

});

if(null!=cachedImage){

  iv.setImageDrawable(cachedImage);

}

 

 

类似于上面的另一种实现方式:

public class AsyncImageLoader{

  private HashMap<String, Bitmap> imageMap; // 存放图片列表:key-图片路径;value-Bitmap

  private Handler handler; 

  // 构造函数

  public AsyncImageLoader(){

    imageMap = new HashMap<String, Bitmap>();

    handler = new Handler();

  }

  // 异步加载图片

  public void loadImage(final String imageUrl,final ImageView imageView){

    new Thread(new Runnable() {
      public void run() {

        Bitmap image = imageMap.get(imageUrl); // 从缓存中获取数据
        if (image == null) {

          image = ApacheUtility.GetBitmapByUrl(imageUrl); // 调用前面 ApacheUtility 类的方法

          imageMap.put(status.getId(), image);

        }

        final Bitmap bitmap = image;
        handler.post(new Runnable() {
          public void run() {
            imgView.setImageBitmap(bitmap);
          }
        });

      }
    }).start();

  }

}

调用过程如下:

String imgUrl="http://www.streetcar.org/mim/cable/images/cable-01.jpg"; // 图片路径

AsyncImageLoader  imagLoader = new AsyncImageLoader();

imageLoader.loadImage(imgUrl,iv); // iv为ImageView实例


转自:http://www.cnblogs.com/beijia/archive/2012/05/08/asyncLoad.html