Android开发中经常会对图片进行处理,图片如何加载和缓存的实现有难有易,这里实现一个简单的ImageLoader,只是简述其中的基本原理。
整个实现需要用到图片的缓存和加载,首先需要实现图片的缓存。Android手机缓存又分别可以用到内存和sd卡,内存实现ImageCache
public class ImageCache { LruCache<String, Bitmap> mImageCache; public ImageCache() { // TODO Auto-generated constructor stub initImageCache(); } private void initImageCache() { // 计算可使用的最大内存 final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024); // 取四分之一的可用内存作为缓存 final int cacheSize = maxMemory / 4; mImageCache = new LruCache<String, Bitmap>(cacheSize) { protected int sizeOf(String key, Bitmap bitmap) { return bitmap.getRowBytes() * bitmap.getHeight() / 1024; }; }; } public void put(String url, Bitmap bitmap) { mImageCache.put(url, bitmap); } public Bitmap get(String url) { return mImageCache.get(url); } }
DiskCache类实现图片缓存到SD卡中
public class DiskCache { static String cacheDir = "sd卡的路径"; // 从缓存中获取图片 public Bitmap get(String url) { return BitmapFactory.decodeFile(cacheDir + url); } // 将图片缓存到内存中 public void put(String url, Bitmap bitmap) { FileOutputStream fileOutputStream = null; try { fileOutputStream = new FileOutputStream(cacheDir + url); bitmap.compress(CompressFormat.PNG, 100, fileOutputStream); } catch (Exception e) { // TODO: handle exception } finally { if (fileOutputStream!=null) { try { fileOutputStream.close(); } catch (Exception e2) { // TODO: handle exception } } } } }
最后在ImageLoader类中分别实现两个缓存:
public class ImageLoader { // 图片缓存 内存缓存 ImageCache mImageCache = new ImageCache(); // SD卡缓存 DiskCache mDiskCache = new DiskCache(); // 是否使用SD卡缓存 boolean isUseDiskCache = false; // 线程池,线程数量为CPU数量 ExecutorService mExecutorService = Executors.newFixedThreadPool(Runtime .getRuntime().availableProcessors()); public void displayImage(final String url, final ImageView imageView) { Bitmap bitmap = isUseDiskCache ? mDiskCache.get(url) : mImageCache .get(url); if (bitmap != null) { imageView.setImageBitmap(bitmap); return; } imageView.setTag(url); mExecutorService.submit(new Runnable() { @Override public void run() { // TODO Auto-generated method stub Bitmap bitmap = downloadImage(url); if (bitmap == null) { return; } if (imageView.getTag().equals(url)) { imageView.setImageBitmap(bitmap); } mImageCache.put(url, bitmap); } }); } public Bitmap downloadImage(String imageUrl) { Bitmap bitmap = null; try { URL url = new URL(imageUrl); final HttpURLConnection conn = (HttpURLConnection) url .openConnection(); bitmap = BitmapFactory.decodeStream(conn.getInputStream()); conn.disconnect(); } catch (Exception e) { // TODO: handle exception } return bitmap; } public void useDiskCache(boolean useDiskCache) { isUseDiskCache = useDiskCache; } }