ImageLoader实现Bitmap三级缓存

对开发艺术中的ImageLoader作了下整理。

三级缓存分别为 内存, 硬盘, 网络 , 其中内存与硬盘存储用到 LruCache与DiskLruCache.
用法会封装在工具类里面,先看ImageLoader的实现步骤
1. 单例实现ImageLoader, 构造方法中开启LruCache与DiskLruCache
2. 三个私有化方法,分别从缓存中取出Bitmap
3. 同步加载方法 loadBitmap
4. 异步加载方法 bindBitmap, 开启线程放入线程池中去执行, 线程中调用同步方法
5. 定义出线程池
6. 定义handler,在handler中去设置imageView

LruCacheDiskCache的代码都被封装到的工具类,这个类结构已经相当清晰。下面是源码

public class ImageLoader {
    private static final String TAG = "ImageLoader";
    private static final int TAG_KEY_URL = R.id.ivIcon;
    private static final int MESSAGE_POST_RESULT = 1;
    private Context mContext;
    private LruCache mMemoryCache;
    private DiskLruCache mDiskCache;

    private static final long DISK_CACHE_SIZE = 1024 * 1024 * 10; // 指定DiskLruCache缓存空间大小  10M的空间
    private static final String CACHE_DIR_NAME = "bitmap"; // 缓存文件夹名称
    private static final int MEMORY_CACHE_SIZE = (int) (Runtime.getRuntime().maxMemory() / 1024) / 8; //指定LruCache缓存大小 内存的八分之一

    /****************线程池相关参数********************/
    private static final int CORE_POOL_SIZE = Runtime.getRuntime().availableProcessors() + 1;
    private static final int MAX_POOL_SIZE = CORE_POOL_SIZE * 2;
    private static final int KEEP_ALIVE = 10;
    private static final ThreadFactory sThreadFactory = new ThreadFactory() {
        private final AtomicInteger mCount = new AtomicInteger();
        @Override
        public Thread newThread(Runnable r) {
            return new Thread(r, "ImageLoader#" + mCount.getAndIncrement());
        }
    };

    // 创建线程池
    private static final Executor THREAD_POOL_EXECUTOR = new ThreadPoolExecutor(CORE_POOL_SIZE, MAX_POOL_SIZE, KEEP_ALIVE,
            TimeUnit.SECONDS, new LinkedBlockingDeque(), sThreadFactory);

    // 实现运行在主线程的handler
    private Handler mHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            LoadResult result = (LoadResult) msg.obj;
            ImageView imageView = result.imageView;
            String url = (String) imageView.getTag(TAG_KEY_URL);
            if (url.equals(result.url)) { //解决加载出来后,ImageView已经滑过的问题
                imageView.setImageBitmap(result.bitmap);
            } else {
                Log.w(TAG, "set image bitmap ,but url has changed , ignored");
            }
        }
    };


    private ImageLoader(Context context) {
        mContext = context;
        mMemoryCache = ImageUtil.openLruCache(MEMORY_CACHE_SIZE);
        mDiskCache = ImageUtil.openDiskLruCache(mContext, DISK_CACHE_SIZE, CACHE_DIR_NAME);
    }

    public static ImageLoader build(Context context) {
        return new ImageLoader(context);
    }


    /**
     * 把bitmap放入内存中
     * @param key
     * @param bitmap
     */
    private void addBitmap2MemoryCache(String key, Bitmap bitmap) {
        if (loadBitmMapFromMemoryCache(key) == null) {
            mMemoryCache.put(key, bitmap);
        }
    }

    /**
     * 从内存中加载
     * @param key
     * @return
     */
    private Bitmap loadBitmMapFromMemoryCache(String key) {
        return mMemoryCache.get(key);
    }

    /**
     * 从磁盘中加载
     * @param url
     * @param reqWidth
     * @param reqHeight
     * @return
     */
    private Bitmap loadBitmapFromDiskCache(String url, int reqWidth, int reqHeight) {
        Bitmap bitmap =  ImageUtil.getFromDiskLruCache(url, mDiskCache, reqWidth, reqHeight);
        if (bitmap != null) { //放入到内存中
            mMemoryCache.put(url, bitmap);
        }
        return bitmap;
    }

    /**
     * 从网络中加载
     * @param url
     * @param reqWidth
     * @param reqHeight
     * @return
     */
    private Bitmap loadBitmapFromHttp(String url, int reqWidth, int reqHeight) {
        if (Looper.myLooper() == Looper.getMainLooper()) { //判断是否在主线程
            throw new RuntimeException("can not visit net work from UI Thread");
        }
        if (mDiskCache == null) {
            return null;
        }
        String key = ImageUtil.encode(url);
        ImageUtil.put2DisLruCache(url, mDiskCache);
        return loadBitmapFromDiskCache(url, reqWidth, reqHeight);
    }

    /**
     * 同步加载
     * @return
     */
    public Bitmap loadBitmap(String url, int reqWidth, int reqHeight) {
        Bitmap bitmap = loadBitmMapFromMemoryCache(url);
        if (bitmap != null) {
            Log.d(TAG, "loadBitmMapFromMemoryCache, url:" + url);
            return bitmap;
        }

        bitmap = loadBitmapFromDiskCache(url, reqWidth, reqHeight);
        if (bitmap != null) {
            Log.d(TAG, "loadBitmapFromDiskCache, url:" + url);
            return bitmap;
        }

        bitmap = loadBitmapFromHttp(url, reqWidth, reqHeight);
        Log.d(TAG, "loadBitmapFromHttp, url:" + url);
        if (bitmap != null) {
            Log.d(TAG, "DiskLrucache is not created");
            bitmap = ImageUtil.downLoadImage(url);
        }
        return bitmap;
    }

    /**
     * 异步加载
     * @param url
     * @param imageView
     * @param reqWidth
     * @param reqHeight
     */
    public void bindBitmap(final String url, final ImageView imageView, final int reqWidth, final int reqHeight) {
        imageView.setTag(TAG_KEY_URL, url);
        Bitmap bitmap = loadBitmMapFromMemoryCache(url);
        if (bitmap != null) {
            imageView.setImageBitmap(bitmap);
            return;
        }

        Runnable loadBitmapTask = new Runnable() {
            @Override
            public void run() {
                Bitmap bitmap = loadBitmap(url, reqWidth, reqHeight);
                if (bitmap != null) {
                    LoadResult result = new LoadResult(imageView, url, bitmap);
                    Message msg = mHandler.obtainMessage(MESSAGE_POST_RESULT, result);
                    mHandler.sendMessage(msg);
                }
            }
        };

        THREAD_POOL_EXECUTOR.execute(loadBitmapTask);
    }

    /**
     * 消息的封装实体
     */
    private static class LoadResult {
        public ImageView imageView;
        public String url;
        public Bitmap bitmap;

        public LoadResult(ImageView imageView, String url, Bitmap bitmap) {
            this.imageView = imageView;
            this.url = url;
            this.bitmap = bitmap;
        }
    }
}

下面是工具类中封装了LruCache,DiskCache以及从网络中下载图片的具体实现

public class ImageUtil {

    /**
     * bitmap压缩
     *
     * @param res
     * @param resId
     * @param reqWidth
     * @param reqHeight
     * @return
     */
    public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId, int reqWidth, int reqHeight) {
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeResource(res, resId, options);

        options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeResource(res, resId, options);
    }

    /**
     * 通过文件描述符的方法加载bitmap
     *
     * @param fd
     * @param reqWidth
     * @param reqHeight
     * @return
     */
    public static Bitmap decodeSampledBitmapFromResource(FileDescriptor fd, int reqWidth, int reqHeight) {
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFileDescriptor(fd, null, options);

        options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeFileDescriptor(fd, null, options);
    }

    /**
     * 计算压缩比例
     * @param options
     * @param reqWidth
     * @param reqHeight
     * @return
     */
    private static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
        int height = options.outHeight;
        int width = options.outWidth;
        int inSampleSize = 1;
        if (height > reqHeight || width > reqWidth) {
            final int halfHeight = height / 2;
            final int halfWidth = width / 2;
            while ((halfHeight / inSampleSize) >= reqHeight && (halfWidth / inSampleSize) >= reqWidth) {
                inSampleSize *= 2;
            }
        }
        return inSampleSize;
    }


    /**
     * 打开一个LruCache
     *
     * @return
     */
    public static LruCache openLruCache(int caCheSize) {
        LruCache imageCache = new LruCache(caCheSize) {
            @Override
            protected int sizeOf(String key, Bitmap bitmap) { //返回bitmap的大小
                return bitmap.getRowBytes() * bitmap.getHeight() / 1024;
            }
        };
        return imageCache;
    }

    /**
     * 打开DiskLruCache
     *
     * @param context
     * @return
     */
    public static DiskLruCache openDiskLruCache(Context context, long maxSize, String cacheDirName) {
        DiskLruCache diskLruCache = null;
        File cacheDir = getDiskCacheDir(context, cacheDirName);
        if (!cacheDir.exists()) {
            cacheDir.mkdirs();
        }
        Log.i("cacheDir", cacheDir.getPath());
        try {
            if (getUsableSpace(cacheDir) > maxSize) {
                diskLruCache = DiskLruCache.open(cacheDir, getAppVersion(context), 1, maxSize);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return diskLruCache;
    }

    /**
     * 获取缓存路径
     *
     * @param context
     * @param name
     * @return
     */
    private static File getDiskCacheDir(Context context, String name) {
        String cacheDir;
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())
                || !Environment.isExternalStorageRemovable()) {
            cacheDir = context.getExternalCacheDir().getPath();
        } else {
            cacheDir = context.getCacheDir().getPath();
        }
        return new File(cacheDir + File.separator + name);
    }

    /**
     * 获取系统版本号
     *
     * @param context
     * @return
     */
    public static int getAppVersion(Context context) {
        try {
            PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
            return packageInfo.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return 1;
    }

    /**
     * MD5加密
     *
     * @param url
     * @return
     */
    public static String encode(String url) {
        try {
            MessageDigest digest = MessageDigest.getInstance("MD5");
            byte[] result = digest.digest(url.getBytes());
            StringBuffer sb = new StringBuffer();
            for (byte b : result) {
                int num = b & 0xff;
                String str = Integer.toHexString(num);
                if (str.length() == 1) {
                    sb.append("0");
                }
                sb.append(str);
            }
            return sb.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            // can't reach
            return "";
        }
    }


    /**
     * 获取可用空间
     * @param path
     * @return
     */
    public static long getUsableSpace(File path) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
            return path.getUsableSpace();
        }
        StatFs stats = new StatFs(path.getPath());
        return stats.getBlockSizeLong() * stats.getAvailableBlocksLong();
    }

    /**
     * 下载图片
     *
     * @param urlString
     * @param outputStream
     * @return
     */
    public static boolean downLoadImage(String urlString, OutputStream outputStream) {
        HttpURLConnection urlConnection = null;
        BufferedOutputStream out = null;
        BufferedInputStream in = null;
        try {
            final URL url = new URL(urlString);
            urlConnection = (HttpURLConnection) url.openConnection();
            in = new BufferedInputStream(urlConnection.getInputStream(), 8 * 1024);
            out = new BufferedOutputStream(outputStream, 8 * 1024);
            int b;
            while ((b = in.read()) != -1) {
                out.write(b);
            }
            return true;
        } catch (final IOException e) {
            e.printStackTrace();
        } finally {
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (final IOException e) {
                e.printStackTrace();
            }
        }
        return false;
    }

    /**
     * 下载图片
     * @param urlString
     * @return bitmap
     */
    public static Bitmap downLoadImage(String urlString) {
        HttpURLConnection urlConnection = null;
        BufferedInputStream in = null;
        Bitmap bitmap = null;
        try {
            final URL url = new URL(urlString);
            urlConnection = (HttpURLConnection) url.openConnection();
            in = new BufferedInputStream(urlConnection.getInputStream(), 8 * 1024);
            BitmapFactory.decodeStream(in);
        } catch (final IOException e) {
            e.printStackTrace();
        } finally {
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
            try {
                if (in != null) {
                    in.close();
                }
            } catch (final IOException e) {
                e.printStackTrace();
            }
        }
        return bitmap;
    }

    /**
     * 加载一个图片放入DisLruCache
     *
     * @param imageUrl
     * @param disLruCache
     */
    public static void put2DisLruCache(String imageUrl, DiskLruCache disLruCache) {
        String key = ImageUtil.encode(imageUrl);

        DiskLruCache.Editor editor = null;
        try {
            editor = disLruCache.edit(key);
            if (editor != null) {
                OutputStream outputStream = editor.newOutputStream(0);
                boolean success = ImageUtil.downLoadImage(imageUrl, outputStream);
                if (success) {
                    editor.commit();
                } else {
                    editor.abort();
                }
            }
            disLruCache.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 从DiskLruCache中取bitmap
     * @param imageUrl
     * @param disLruCache
     * @param reqWidth
     * @param reqHeight
     * @return
     */
    public static Bitmap getFromDiskLruCache(String imageUrl, DiskLruCache disLruCache, int reqWidth, int reqHeight) {
        try {
            String key = encode(imageUrl);
            DiskLruCache.Snapshot snapshot = disLruCache.get(key);
            if (snapshot != null) {
                FileInputStream inputStream = (FileInputStream) snapshot.getInputStream(0);
                FileDescriptor fd = inputStream.getFD();
                Bitmap bitmap = decodeSampledBitmapFromResource(fd, reqWidth, reqHeight);
                return bitmap;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}

你可能感兴趣的:(android进阶)