Example usage for android.graphics Bitmap getRowBytes

List of usage examples for android.graphics Bitmap getRowBytes

Introduction

In this page you can find the example usage for android.graphics Bitmap getRowBytes.

Prototype

public final int getRowBytes() 

Source Link

Document

Return the number of bytes between rows in the bitmap's pixels.

Usage

From source file:com.ohso.util.ImageHandler.java

public ImageHandler(Activity activity) {
    MEMORY_CLASS = ((ActivityManager) activity.getSystemService(Context.ACTIVITY_SERVICE)).getMemoryClass();
    MEMORY_CACHE_SIZE = 1024 * 1024 * MEMORY_CLASS / 8; // Use 1/8 the available memory
    mMemoryCache = new LruCache<String, Bitmap>(MEMORY_CACHE_SIZE) {
        protected int sizeOf(String key, Bitmap bitmap) {
            return bitmap.getRowBytes() * bitmap.getHeight();
        }//from  w  ww.j  a v a2s  . c o m
    };
    File cacheDir = new File(activity.getCacheDir(), "thumbnails");
    try {
        mDiskCache = DiskLruCache.open(cacheDir, 1, 1, DISK_CACHE_SIZE);
    } catch (IOException e) {
        e.printStackTrace();
    }
    mPixelSize = scaledDIP(IMAGE_DIMENSIONS);
    mPlaceholderParams = new RelativeLayout.LayoutParams((int) mPixelSize, (int) mPixelSize);
    mPlaceholderParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
    mPlaceholderParams.topMargin = 0;
}

From source file:com.nttec.everychan.cache.BitmapCache.java

/**
 * ?//  w ww  . j  a  v  a 2  s  . co m
 * @param maxSize ?  ?  ?  
 * @param fileCache   ?
 */
public BitmapCache(int maxSize, FileCache fileCache) {
    this.fileCache = fileCache;
    this.lru = new LruCache<String, Bitmap>(maxSize) {
        @Override
        protected int sizeOf(String key, Bitmap value) {
            return value.getRowBytes() * value.getHeight();
        }
    };
    this.currentDownloads = new HashSet<String>();
}

From source file:com.isaacrf.epicbitmaprenderer.core.EpicBitmapCache.java

/**
 * Basic constructor, builds the memory cache automatically.
 *///w w  w .jav a 2  s. c o m
public EpicBitmapCache() {
    // Get max available VM memory, exceeding this amount will throw an
    // OutOfMemory exception. Stored in kilobytes as LruCache takes an
    // int in its constructor.
    final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
    // Use 1/8th of the available memory for this memory cache.
    final int cacheSize = maxMemory / 8;

    //Initialize the memory cache
    mMemoryCache = new LruCache<String, Bitmap>(cacheSize) {
        @Override
        protected int sizeOf(String key, Bitmap bitmap) {
            // The cache size will be measured in kilobytes rather than
            // number of items.
            return (bitmap.getRowBytes() * bitmap.getHeight()) / 1024;
        }
    };
}

From source file:net.gree.asdk.core.imageloader.cache.ImageCache.java

@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR1)
private int getBitmapSize(Bitmap bitmap) {
    if (Util.hasHoneycombMR1()) {
        return bitmap.getByteCount();
    }//  w w w . j  a  v a  2s.c  o  m
    return bitmap.getRowBytes() * bitmap.getHeight();
}

From source file:com.meg7.soas.util.BitmapLruCache.java

@SuppressLint("NewApi")
@Override//w  w  w  .j av  a  2 s  .  c o  m
protected int sizeOf(String key, Bitmap bitmap) {
    // The cache size will be measured in kilobytes rather than
    // number of items.
    if (Build.VERSION.SDK_INT >= VERSION_CODES.KITKAT) {
        return bitmap.getAllocationByteCount() / 1024;
    } else if (Build.VERSION.SDK_INT >= VERSION_CODES.HONEYCOMB_MR1) {
        return bitmap.getByteCount() / 1024;
    } else {
        return bitmap.getRowBytes() * bitmap.getHeight() / 1024;
    }
}

From source file:com.githang.androidkit.cache.BitmapLruCache.java

/**
 * ?//  ww w  . j  av a2s.c om
 */
private void initCache() {
    if (mParams.isMemCacheEnabled()) {
        if (BuildConfig.DEBUG) {
            log.d("Memory cache created (size = " + mParams.getMemCacheSize() + "B)");
        }
        mMemoryCache = new LruCache<String, Bitmap>(mParams.getMemCacheSize()) {
            @Override
            protected int sizeOf(String key, Bitmap bitmap) {
                return bitmap.getRowBytes() * bitmap.getHeight();
            }
        };
    }
    // Set up disk cache
    initDiskCache();
}

From source file:com.witheyjr.listviewanimator.StableWrapperArrayAdapter.java

public StableWrapperArrayAdapter(Context context, int layoutResourceId, List<ContentsWrapper> origObjects) {
    super(context, layoutResourceId, origObjects);
    this.mObjects = origObjects;
    for (int i = 0; i < mObjects.size(); ++i) {
        mIdMap.put(mObjects.get(i), i);//www  .  j  av  a 2  s.c o m
    }
    this.mContext = context;
    this.mLayoutResourceId = layoutResourceId;
    withImage = true;
    /* Get max available VM memory, exceeding this amount will throw an OutOfMemory exception. 
     * Stored in kilobytes as LruCache takes an int in its constructor.*/
    final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
    // Use 1/4 of the available memory for this memory cache.
    final int cacheSize = maxMemory / 4;
    mMemoryCache = new LruCache<String, Bitmap>(cacheSize) {
        @SuppressLint("NewApi")
        @Override
        protected int sizeOf(String key, Bitmap bitmap) {
            // The cache size will be measured in kilobytes rather than number of items. Also, I love fragmentation.
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB_MR1) {
                return (bitmap.getRowBytes() * bitmap.getHeight()) / 1024;
            } else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
                return bitmap.getByteCount() / 1024;
            } else {
                return bitmap.getAllocationByteCount() / 1024;
            }
        }
    };
}

From source file:org.matrix.androidsdk.db.MXMediaDownloadWorkerTask.java

/**
 * Search a cached bitmap from an url.//from   w w  w . j a v a 2 s. co  m
 * rotationAngle is set to Integer.MAX_VALUE when undefined : the EXIF metadata must be checked.
 *
 * @param baseFile the base file
 * @param url the media url
 * @param rotation the bitmap rotation
 * @param mimeType the mime type
 * @return the cached bitmap
 */
public static Bitmap bitmapForURL(Context context, File baseFile, String url, int rotation, String mimeType) {
    Bitmap bitmap = null;

    // sanity check
    if (null != url) {

        if (null == mBitmapByUrlCache) {
            int lruSize = Math.min(20 * 1024 * 1024, (int) Runtime.getRuntime().maxMemory() / 8);

            Log.d(LOG_TAG, "bitmapForURL  lruSize : " + lruSize);

            mBitmapByUrlCache = new LruCache<String, Bitmap>(lruSize) {
                @Override
                protected int sizeOf(String key, Bitmap bitmap) {
                    return bitmap.getRowBytes() * bitmap.getHeight(); // size in bytes
                }
            };
        }

        // the image is downloading in background
        if (null != getMediaDownloadWorkerTask(url)) {
            return null;
        }

        // the url is invalid
        if (isMediaUrlUnreachable(url)) {
            return null;
        }

        synchronized (mSyncObject) {
            bitmap = mBitmapByUrlCache.get(url);
        }

        // check if the image has not been saved in file system
        if ((null == bitmap) && (null != baseFile)) {
            String filename = null;

            // the url is a file one
            if (url.startsWith("file:")) {
                // try to parse it
                try {
                    Uri uri = Uri.parse(url);
                    filename = uri.getPath();

                } catch (Exception e) {
                    Log.e(LOG_TAG, "bitmapForURL #1 : " + e.getLocalizedMessage());
                }

                // cannot extract the filename -> sorry
                if (null == filename) {
                    return null;
                }
            }

            // not a valid file name
            if (null == filename) {
                filename = buildFileName(url, mimeType);
            }

            try {
                File file = filename.startsWith(File.separator) ? new File(filename)
                        : new File(baseFile, filename);

                if (!file.exists()) {
                    Log.d(LOG_TAG, "bitmapForURL() : " + filename + " does not exist");
                    return null;
                }

                InputStream fis = new FileInputStream(file);

                // read the metadata
                if (Integer.MAX_VALUE == rotation) {
                    rotation = ImageUtils.getRotationAngleForBitmap(context, Uri.fromFile(file));
                }

                if (null != fis) {
                    BitmapFactory.Options options = new BitmapFactory.Options();
                    options.inPreferredConfig = Bitmap.Config.ARGB_8888;

                    try {
                        bitmap = BitmapFactory.decodeStream(fis, null, options);
                    } catch (OutOfMemoryError error) {
                        System.gc();
                        Log.e(LOG_TAG, "bitmapForURL() : Out of memory 1 " + error);
                    }

                    //  try again
                    if (null == bitmap) {
                        try {
                            bitmap = BitmapFactory.decodeStream(fis, null, options);
                        } catch (OutOfMemoryError error) {
                            Log.e(LOG_TAG, "bitmapForURL() Out of memory 2" + error);
                        }
                    }

                    if (null != bitmap) {
                        synchronized (mSyncObject) {
                            if (0 != rotation) {
                                try {
                                    android.graphics.Matrix bitmapMatrix = new android.graphics.Matrix();
                                    bitmapMatrix.postRotate(rotation);

                                    Bitmap transformedBitmap = Bitmap.createBitmap(bitmap, 0, 0,
                                            bitmap.getWidth(), bitmap.getHeight(), bitmapMatrix, false);
                                    bitmap.recycle();
                                    bitmap = transformedBitmap;
                                } catch (OutOfMemoryError ex) {
                                    Log.e(LOG_TAG, "bitmapForURL rotation error : " + ex.getLocalizedMessage());
                                }
                            }

                            // cache only small images
                            // caching large images does not make sense
                            // it would replace small ones.
                            // let assume that the application must be faster when showing the chat history.
                            if ((bitmap.getWidth() < 1000) && (bitmap.getHeight() < 1000)) {
                                mBitmapByUrlCache.put(url, bitmap);
                            }
                        }
                    }

                    fis.close();
                }

            } catch (FileNotFoundException e) {
                Log.d(LOG_TAG, "bitmapForURL() : " + filename + " does not exist");
            } catch (Exception e) {
                Log.e(LOG_TAG, "bitmapForURL() " + e);

            }
        }
    }

    return bitmap;
}

From source file:com.floyd.diamond.IMImageCache.java

/**
 * Initialize the cache, providing all parameters.
 *
 * @param context     The context to use
 * @param cacheParams The cache parameters to initialize the cache
 */// ww w  .java2s  .  com
private void init(Context context, ImageCacheParams cacheParams) {
    // final File diskCacheDir = DiskLruCache.getDiskCacheDir(context,
    // cacheParams.uniqueName);

    // Set up disk cache
    //      if (cacheParams.diskCacheEnabled) {
    //         mDiskCache = new WxImageDiskCache(cacheParams.uniqueName);
    //      }

    // Set up memory cache
    if (cacheParams.memoryCacheEnabled) {
        mMemoryCache = new LruCache<String, Bitmap>(cacheParams.memCacheSize) {
            /**
             * Measure item size in bytes rather than units which is more
             * practical for a bitmap cache
             */
            @SuppressLint("NewApi")
            @Override
            protected int sizeOf(String key, Bitmap bitmap) {
                // int size = bitmap.getRowBytes() * bitmap.getHeight();
                // Log.d("setting", "Bitmap size:" + size);
                int size = 0;
                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB_MR1) {
                    size = bitmap.getRowBytes() * bitmap.getHeight();
                } else {
                    size = bitmap.getByteCount();
                }
                return size;
            }
        };
    }

}

From source file:com.gsbabil.antitaintdroid.UtilityFunctions.java

/**
 * Source:/*from  w w w .  j av  a  2s  . c  om*/
 * http://stackoverflow.com/questions/4349075/bitmapfactory-decoderesource
 * -returns-a-mutable-bitmap-in-android-2-2-and-an-immu
 * 
 * Converts a immutable bitmap to a mutable bitmap. This operation doesn't
 * allocates more memory that there is already allocated.
 * 
 * @param imgIn
 *            - Source image. It will be released, and should not be used
 *            more
 * @return a copy of imgIn, but immutable.
 */
public static Bitmap convertBitmapToMutable(Bitmap imgIn) {
    try {
        // this is the file going to use temporally to save the bytes.
        // This file will not be a image, it will store the raw image data.
        File file = new File(MyApp.context.getFilesDir() + File.separator + "temp.tmp");

        // Open an RandomAccessFile
        // Make sure you have added uses-permission
        // android:name="android.permission.WRITE_EXTERNAL_STORAGE"
        // into AndroidManifest.xml file
        RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");

        // get the width and height of the source bitmap.
        int width = imgIn.getWidth();
        int height = imgIn.getHeight();
        Config type = imgIn.getConfig();

        // Copy the byte to the file
        // Assume source bitmap loaded using options.inPreferredConfig =
        // Config.ARGB_8888;
        FileChannel channel = randomAccessFile.getChannel();
        MappedByteBuffer map = channel.map(MapMode.READ_WRITE, 0, imgIn.getRowBytes() * height);
        imgIn.copyPixelsToBuffer(map);
        // recycle the source bitmap, this will be no longer used.
        imgIn.recycle();
        System.gc();// try to force the bytes from the imgIn to be released

        // Create a new bitmap to load the bitmap again. Probably the memory
        // will be available.
        imgIn = Bitmap.createBitmap(width, height, type);
        map.position(0);
        // load it back from temporary
        imgIn.copyPixelsFromBuffer(map);
        // close the temporary file and channel , then delete that also
        channel.close();
        randomAccessFile.close();

        // delete the temporary file
        file.delete();

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

    return imgIn;
}