Android Open Source - ion Ion Bitmap Cache






From Project

Back to project page ion.

License

The source code is released under:

Apache License

If you think the Android project ion listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.

Java Source Code

package com.koushikdutta.ion.bitmap;
/*from w  w w .j  a v a 2 s . c o  m*/
import android.annotation.TargetApi;
import android.app.ActivityManager;
import android.content.Context;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapRegionDecoder;
import android.graphics.Matrix;
import android.graphics.Point;
import android.graphics.Rect;
import android.os.Build;
import android.os.Looper;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.WindowManager;

import com.koushikdutta.async.util.StreamUtility;
import com.koushikdutta.ion.Ion;

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

/**
 * Created by koush on 5/23/13.
 */
public class IonBitmapCache {
    public static final long DEFAULT_ERROR_CACHE_DURATION = 30000L;

    Resources resources;
    DisplayMetrics metrics;
    LruBitmapCache cache;
    Ion ion;
    long errorCacheDuration = DEFAULT_ERROR_CACHE_DURATION;

    public long getErrorCacheDuration() {
        return errorCacheDuration;
    }

    public void setErrorCacheDuration(long errorCacheDuration) {
        this.errorCacheDuration = errorCacheDuration;
    }

    public IonBitmapCache(Ion ion) {
        Context context = ion.getContext().getApplicationContext();
        this.ion = ion;
        metrics = new DisplayMetrics();
        ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE))
                .getDefaultDisplay().getMetrics(metrics);
        final AssetManager mgr = context.getAssets();
        resources = new Resources(mgr, metrics, context.getResources().getConfiguration());
        cache = new LruBitmapCache(getHeapSize(context) / 7);
    }

    public BitmapInfo remove(String key) {
        return cache.removeBitmapInfo(key);
    }

    public void clear() {
        cache.evictAllBitmapInfo();
    }

    double heapRatio = 1d / 7d;
    public double getHeapRatio() {
        return heapRatio;
    }

    public void setHeapRatio(double heapRatio) {
        this.heapRatio = heapRatio;
    }

    public void put(BitmapInfo info) {
        assert Thread.currentThread() == Looper.getMainLooper().getThread();
        int maxSize = (int)(getHeapSize(ion.getContext()) * heapRatio);
        if (maxSize != cache.maxSize())
            cache.setMaxSize(maxSize);
        cache.put(info.key, info);
    }

    public void putSoft(BitmapInfo info) {
        assert Thread.currentThread() == Looper.getMainLooper().getThread();
        cache.putSoft(info.key, info);
    }

    public BitmapInfo get(String key) {
        if (key == null)
            return null;

        // see if this thing has an immediate cache hit
        BitmapInfo ret = cache.getBitmapInfo(key);
        if (ret == null || ret.exception == null)
            return ret;

        // if this bitmap load previously errored out, see if it is time to retry
        // the fetch. connectivity error, server failure, etc, shouldn't be
        // cached indefinitely...
        if (ret.loadTime + errorCacheDuration > System.currentTimeMillis())
            return ret;

        cache.remove(key);
        return null;
    }

    public void dump() {
        Log.i("IonBitmapCache", "bitmap cache: " + cache.size());
        Log.i("IonBitmapCache", "freeMemory: " + Runtime.getRuntime().freeMemory());
    }

    private Point computeTarget(int minx, int miny) {
        int targetWidth = minx;
        int targetHeight = miny;
        if (targetWidth == 0)
            targetWidth = metrics.widthPixels;
        if (targetWidth <= 0)
            targetWidth = Integer.MAX_VALUE;
        if (targetHeight == 0)
            targetHeight = metrics.heightPixels;
        if (targetHeight <= 0)
            targetHeight = Integer.MAX_VALUE;
        return new Point(targetWidth, targetHeight);
    }

  private BitmapFactory.Options prepareBitmapOptions(BitmapFactory.Options o, int minx, int miny) throws BitmapDecodeException {
        if (o.outWidth < 0 || o.outHeight < 0)
            throw new BitmapDecodeException(o.outWidth, o.outHeight);
        Point target = computeTarget(minx, miny);
        int scale = Math.max(o.outWidth / target.x, o.outHeight / target.y);
        BitmapFactory.Options ret = new BitmapFactory.Options();
        ret.inSampleSize = scale;
        ret.outWidth = o.outWidth;
        ret.outHeight = o.outHeight;
        ret.outMimeType = o.outMimeType;
        return ret;
    }

    public BitmapFactory.Options prepareBitmapOptions(File file, int minx, int miny) throws BitmapDecodeException {
        BitmapFactory.Options o = new BitmapFactory.Options();
        o.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(file.toString(), o);
        return prepareBitmapOptions(o, minx, miny);
    }

    public BitmapFactory.Options prepareBitmapOptions(byte[] bytes, int offset, int length, int minx, int miny) throws BitmapDecodeException {
        BitmapFactory.Options o = new BitmapFactory.Options();
        o.inJustDecodeBounds = true;
        BitmapFactory.decodeByteArray(bytes, offset, length, o);
        return prepareBitmapOptions(o, minx, miny);
    }

    public BitmapFactory.Options prepareBitmapOptions(Resources res, int id, int minx, int miny) throws BitmapDecodeException {
        BitmapFactory.Options o = new BitmapFactory.Options();
        o.inJustDecodeBounds = true;
        BitmapFactory.decodeResource(res, id, o);
        return prepareBitmapOptions(o, minx, miny);
    }

    public BitmapFactory.Options prepareBitmapOptions(InputStream in, int minx, int miny) throws BitmapDecodeException {
        BitmapFactory.Options o = new BitmapFactory.Options();
        o.inJustDecodeBounds = true;
        BitmapFactory.decodeStream(in, null, o);
        return prepareBitmapOptions(o, minx, miny);
    }

    private static Bitmap getRotatedBitmap(Bitmap bitmap, int rotation) {
        if (bitmap == null)
            return null;
        if (rotation == 0)
            return bitmap;

        Matrix matrix = new Matrix();
        matrix.postRotate(rotation);
        return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
    }

    public static Bitmap loadBitmap(byte[] bytes, int offset, int length, BitmapFactory.Options o) {
        assert Thread.currentThread() != Looper.getMainLooper().getThread();

        Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, offset, length, o);
        if (bitmap == null)
            return null;
        int rotation = Exif.getOrientation(bytes, offset, length);
        return getRotatedBitmap(bitmap, rotation);
    }

    @TargetApi(Build.VERSION_CODES.GINGERBREAD_MR1)
    public static Bitmap loadRegion(final BitmapRegionDecoder decoder, Rect sourceRect, int inSampleSize) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inSampleSize = inSampleSize;
        return decoder.decodeRegion(sourceRect, options);
    }

    public static Bitmap loadBitmap(Resources res, int id, BitmapFactory.Options o) {
        assert Thread.currentThread() != Looper.getMainLooper().getThread();

        int rotation;
        InputStream in = null;
        try {
            in = res.openRawResource(id);
            byte[] bytes = new byte[50000];
            int length = in.read(bytes);
            rotation = Exif.getOrientation(bytes, 0, length);
        }
        catch (Exception e) {
            rotation = 0;
        }
        StreamUtility.closeQuietly(in);

        Bitmap bitmap = BitmapFactory.decodeResource(res, id, o);
        return getRotatedBitmap(bitmap, rotation);
    }

    public static Bitmap loadBitmap(InputStream stream, BitmapFactory.Options o) throws IOException {
        assert Thread.currentThread() != Looper.getMainLooper().getThread();

        int rotation;
        MarkableInputStream in = new MarkableInputStream(stream);
        in.mark(50000);
        try {
            byte[] bytes = new byte[50000];
            int length = in.read(bytes);
            rotation = Exif.getOrientation(bytes, 0, length);
        }
        catch (Exception e) {
            rotation = 0;
        }
        in.reset();

        Bitmap bitmap = BitmapFactory.decodeStream(in, null, o);
        return getRotatedBitmap(bitmap, rotation);
    }

    public static Bitmap loadBitmap(File file, BitmapFactory.Options o) {
        assert Thread.currentThread() != Looper.getMainLooper().getThread();

        int rotation;
        FileInputStream fin = null;
        try {
            fin = new FileInputStream(file);
            byte[] bytes = new byte[50000];
            int length = fin.read(bytes);
            rotation = Exif.getOrientation(bytes, 0, length);
        }
        catch (Exception e) {
            rotation = 0;
        }
        StreamUtility.closeQuietly(fin);

        Bitmap bitmap = BitmapFactory.decodeFile(file.toString(), o);
        return getRotatedBitmap(bitmap, rotation);
    }

    private static int getHeapSize(final Context context) {
        return ((ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE)).getMemoryClass() * 1024 * 1024;
    }
}




Java Source Code List

com.koushikdutta.ion.BitmapCallback.java
com.koushikdutta.ion.BitmapFetcher.java
com.koushikdutta.ion.BitmapInfoToBitmap.java
com.koushikdutta.ion.ContextReference.java
com.koushikdutta.ion.DefaultTransform.java
com.koushikdutta.ion.DeferredLoadBitmap.java
com.koushikdutta.ion.FileCacheStore.java
com.koushikdutta.ion.HeadersCallback.java
com.koushikdutta.ion.HeadersResponse.java
com.koushikdutta.ion.ImageViewBitmapInfo.java
com.koushikdutta.ion.ImageViewFutureImpl.java
com.koushikdutta.ion.InputStreamParser.java
com.koushikdutta.ion.IonBitmapRequestBuilder.java
com.koushikdutta.ion.IonDrawable.java
com.koushikdutta.ion.IonImageViewRequestBuilder.java
com.koushikdutta.ion.IonLog.java
com.koushikdutta.ion.IonRequestBuilder.java
com.koushikdutta.ion.Ion.java
com.koushikdutta.ion.LoadBitmapBase.java
com.koushikdutta.ion.LoadBitmapEmitter.java
com.koushikdutta.ion.LoadBitmapRegion.java
com.koushikdutta.ion.LoadBitmap.java
com.koushikdutta.ion.LoadDeepZoom.java
com.koushikdutta.ion.Loader.java
com.koushikdutta.ion.ProgressCallback.java
com.koushikdutta.ion.RequestBodyUploadObserver.java
com.koushikdutta.ion.Response.java
com.koushikdutta.ion.ScaleMode.java
com.koushikdutta.ion.TransformBitmap.java
com.koushikdutta.ion.bitmap.BitmapDecodeException.java
com.koushikdutta.ion.bitmap.BitmapInfo.java
com.koushikdutta.ion.bitmap.Exif.java
com.koushikdutta.ion.bitmap.IonBitmapCache.java
com.koushikdutta.ion.bitmap.LocallyCachedStatus.java
com.koushikdutta.ion.bitmap.LruBitmapCache.java
com.koushikdutta.ion.bitmap.MarkableInputStream.java
com.koushikdutta.ion.bitmap.PostProcess.java
com.koushikdutta.ion.bitmap.SoftReferenceHashtable.java
com.koushikdutta.ion.bitmap.Transform.java
com.koushikdutta.ion.builder.AnimateGifMode.java
com.koushikdutta.ion.builder.BitmapBuilder.java
com.koushikdutta.ion.builder.BitmapFutureBuilder.java
com.koushikdutta.ion.builder.Builders.java
com.koushikdutta.ion.builder.FutureBuilder.java
com.koushikdutta.ion.builder.GsonFutureBuilder.java
com.koushikdutta.ion.builder.ImageViewBuilder.java
com.koushikdutta.ion.builder.ImageViewFutureBuilder.java
com.koushikdutta.ion.builder.LoadBuilder.java
com.koushikdutta.ion.builder.LoadImageViewFutureBuilder.java
com.koushikdutta.ion.builder.MultipartBodyBuilder.java
com.koushikdutta.ion.builder.RequestBuilder.java
com.koushikdutta.ion.builder.UrlEncodedBuilder.java
com.koushikdutta.ion.conscrypt.ConscryptMiddleware.java
com.koushikdutta.ion.cookie.CookieMiddleware.java
com.koushikdutta.ion.future.ImageViewFuture.java
com.koushikdutta.ion.future.ResponseFuture.java
com.koushikdutta.ion.gif.GifDecoder.java
com.koushikdutta.ion.gif.GifFrame.java
com.koushikdutta.ion.gson.GsonArrayParser.java
com.koushikdutta.ion.gson.GsonBody.java
com.koushikdutta.ion.gson.GsonObjectParser.java
com.koushikdutta.ion.gson.GsonParser.java
com.koushikdutta.ion.gson.GsonSerializer.java
com.koushikdutta.ion.gson.PojoBody.java
com.koushikdutta.ion.loader.AssetLoader.java
com.koushikdutta.ion.loader.AsyncHttpRequestFactory.java
com.koushikdutta.ion.loader.ContentLoader.java
com.koushikdutta.ion.loader.FileLoader.java
com.koushikdutta.ion.loader.HttpLoader.java
com.koushikdutta.ion.loader.InputStreamDataEmitterFuture.java
com.koushikdutta.ion.loader.MediaFile.java
com.koushikdutta.ion.loader.MtpConstants.java
com.koushikdutta.ion.loader.PackageIconLoader.java
com.koushikdutta.ion.loader.ResourceLoader.java
com.koushikdutta.ion.loader.SimpleLoader.java
com.koushikdutta.ion.loader.StreamLoader.java
com.koushikdutta.ion.loader.VideoLoader.java
com.koushikdutta.ion.sample.DeepZoomSample.java
com.koushikdutta.ion.sample.GallerySample.java
com.koushikdutta.ion.sample.GoogleImageSearch.java
com.koushikdutta.ion.sample.ImageViewSample.java
com.koushikdutta.ion.sample.LollipopTransitionFullscreen.java
com.koushikdutta.ion.sample.LollipopTransition.java
com.koushikdutta.ion.sample.ProgressBarDownload.java
com.koushikdutta.ion.sample.ProgressBarUpload.java
com.koushikdutta.ion.sample.SampleApplication.java
com.koushikdutta.ion.sample.Samples.java
com.koushikdutta.ion.sample.SquaredImageView.java
com.koushikdutta.ion.sample.TwitterGson.java
com.koushikdutta.ion.sample.Twitter.java