LruCache和DiskLruCache代碼案例

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.os.Environment;
import android.util.Log;
import android.util.LruCache;
import android.view.View;

import com.jakewharton.disklrucache.DiskLruCache;

import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class ImageUtils {

    private static final String TAG = ImageUtils.class.getSimpleName();

    private static LruCache<String, Bitmap> mMemoryCache;

    private static int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
    private static int cacheSize = maxMemory / 8;
    private static final int DEFAULT_DISK_CACHE_SIZE = 1024 * 1024 * 10;
    private static final String DEFAULT_DISK_CACHE_NAME = "thumbnail";
    private static DiskLruCache mDiskLruCache;
    private static final int DISK_CACHE_INDEX = 0;
    private static final Bitmap.CompressFormat DEFAULT_COMPRESS_FORMAT = Bitmap.CompressFormat.JPEG;
    private static final int DEFAULT_COMPRESS_QUALITY = 70;


    private static void initMemoryCache() {
        mMemoryCache = new LruCache<String, Bitmap>(cacheSize) {
            @Override
            protected int sizeOf(String key, Bitmap value) {
                return value.getRowBytes() * value.getHeight() / 1024;

            }

            @Override
            protected void entryRemoved(boolean evicted, String key, Bitmap oldValue, Bitmap newValue) {
                if (oldValue != null && (!oldValue.isRecycled())) {
                    oldValue.recycle();
                }
                super.entryRemoved(evicted, key, oldValue, newValue);
            }
        };
    }

    public static void initDiskLruCache(Context context) {

            if (mDiskLruCache == null || mDiskLruCache.isClosed()) {
                try {
                    File file = getDiskCacheDir(context, DEFAULT_DISK_CACHE_NAME);
                    mDiskLruCache = DiskLruCache.open(file, 1, 1, DEFAULT_DISK_CACHE_SIZE);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
    }

    public static void addBitmapToMemoryCache(String key, Bitmap bitmap) {

        if (mMemoryCache == null) {
            initMemoryCache();
        }

        if (mMemoryCache.get(key) == null) {
            mMemoryCache.put(key, bitmap);
        }

    }

    public static void addBitmapToDiskCache(String key, Bitmap bitmap) {
        if (key != null && bitmap != null) {
                if (mDiskLruCache != null) {
                    OutputStream outputStream = null;
                    try {
                        DiskLruCache.Snapshot snapshot = mDiskLruCache.get(key);

                        if (snapshot == null) {

                            DiskLruCache.Editor editor = mDiskLruCache.edit(key);
                            if (editor != null) {
                                outputStream = editor.newOutputStream(DISK_CACHE_INDEX);
                                assert bitmap != null;
                                bitmap.compress(DEFAULT_COMPRESS_FORMAT, DEFAULT_COMPRESS_QUALITY, outputStream);

                                editor.commit();
                                outputStream.close();
                            }
                        } else {
                            snapshot.getInputStream(DISK_CACHE_INDEX).close();
                        }

                    } catch (IOException e) {
                        e.printStackTrace();
                    } finally {
                        if (outputStream != null) {
                            try {
                                outputStream.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
            }

    }


    public static Bitmap getBitmapFromDiskCache(String key) {
        Bitmap bitmap = null;
            if (mDiskLruCache != null) {
                InputStream inputStream = null;

                try {
                    DiskLruCache.Snapshot snapshot = mDiskLruCache.get(key);
                    if (snapshot != null) {
                        inputStream = snapshot.getInputStream(DISK_CACHE_INDEX);
                        if (inputStream != null) {
                            FileDescriptor fileDescriptor = ((FileInputStream)inputStream).getFD();
                            BitmapFactory.Options options = new BitmapFactory.Options();
                            options.inMutable = true;
                            bitmap = BitmapFactory.decodeFileDescriptor(fileDescriptor, null, options);
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }finally {
                    if (inputStream != null) {
                        try {
                            inputStream.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }

            return bitmap;

    }

    public static Bitmap getBitmapFromMemoryCache(String key) {

        if (mMemoryCache == null) {
            initMemoryCache();
        }

        return mMemoryCache.get(key);
    }

    public static Bitmap convertViewToBitmap(View view, int bitmapWidth, int bitmapHeight) {
        Bitmap bitmap = Bitmap.createBitmap(bitmapWidth, bitmapHeight, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        view.draw(canvas);
        return bitmap;
    }

    public static File getDiskCacheDir(Context context, String uniqueName) {

        if (context == null) {
            Log.d(TAG, "getDiskCacheDir()....context is null!");
            return null;
        }

        boolean isMounted = Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) ||
                !Environment.isExternalStorageRemovable();
        if (isMounted) {
            File externalCacheDir = new File(context.getExternalCacheDir().getPath());
            LogUtils.d(TAG, "getDiskCacheDir()....externalCacheDir is null!");
            return new File(externalCacheDir.getPath() + File.separator + uniqueName);
        } else {
            File cacheDir = context.getCacheDir();
            if (null != cacheDir) {
                LogUtils.d(TAG, "getDiskCacheDir()....context.getCacheDir() == null!");
                return new File(context.getCacheDir().getPath() + File.separator + uniqueName);
            }
        }
        return null;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章