Example usage for android.graphics.drawable BitmapDrawable getBitmap

List of usage examples for android.graphics.drawable BitmapDrawable getBitmap

Introduction

In this page you can find the example usage for android.graphics.drawable BitmapDrawable getBitmap.

Prototype

public final Bitmap getBitmap() 

Source Link

Document

Returns the bitmap used by this drawable to render.

Usage

From source file:com.chanlytech.unicorn.cache.ImageCache.java

@Override
protected LruCache<String, BitmapDrawable> getLurCache() {
    return new LruCache<String, BitmapDrawable>(mCacheParams.MEMORY_CACHE_SIZE) {
        /**//from  www.ja v a 2s .  com
         * Notify the removed entry that is no longer being cached
         */
        @Override
        protected void entryRemoved(boolean evicted, String key, BitmapDrawable oldValue,
                BitmapDrawable newValue) {
            if (RecyclingBitmapDrawable.class.isInstance(oldValue)) {
                // The removed entry is a recycling drawable, so notify it
                // that it has been removed from the memory cache
                ((RecyclingBitmapDrawable) oldValue).setIsCached(false);
            } else {
                // The removed entry is a standard BitmapDrawable

                if (AndroidVersion.hasHoneycomb()) {
                    // We're running on Honeycomb or later, so add the bitmap
                    // to a SoftReference set for possible use with inBitmap later
                    mReusableBitmaps.add(new SoftReference<Bitmap>(oldValue.getBitmap()));
                }
            }
        }

        /**
         * Measure item size in kilobytes rather than units which is more practical
         * for a bitmap cache
         */
        @Override
        protected int sizeOf(String key, BitmapDrawable value) {
            final int bitmapSize = getBitmapSize(value) / 1024;
            return bitmapSize == 0 ? 1 : bitmapSize;
        }
    };
}

From source file:com.higgses.griffin.cache.ImageCache.java

@Override
protected LruCache<String, BitmapDrawable> getLurCache() {
    return new LruCache<String, BitmapDrawable>(mCacheParams.MEMORY_CACHE_SIZE) {
        /**//from  w w w  . j  a va 2 s .  co m
         * Notify the removed entry that is no longer being cached
         */
        @Override
        protected void entryRemoved(boolean evicted, String key, BitmapDrawable oldValue,
                BitmapDrawable newValue) {
            if (RecyclingBitmapDrawable.class.isInstance(oldValue)) {
                // The removed entry is a recycling drawable, so notify it
                // that it has been removed from the memory cache
                ((RecyclingBitmapDrawable) oldValue).setIsCached(false);
            } else {
                // The removed entry is a standard BitmapDrawable

                if (GriUAndroidVersion.hasHoneycomb()) {
                    // We're running on Honeycomb or later, so add the bitmap
                    // to a SoftReference set for possible use with inBitmap later
                    mReusableBitmaps.add(new SoftReference<Bitmap>(oldValue.getBitmap()));
                }
            }
        }

        /**
         * Measure item size in kilobytes rather than units which is more practical
         * for a bitmap cache
         */
        @Override
        protected int sizeOf(String key, BitmapDrawable value) {
            final int bitmapSize = getBitmapSize(value) / 1024;
            return bitmapSize == 0 ? 1 : bitmapSize;
        }
    };
}

From source file:com.seun.gallery.util.ImageCache.java

/**
 * Initialize the cache//w ww .  j a v  a  2 s  .  c  o m
 */
private void init(int memoryCacheSize) {
    //BEGIN_INCLUDE(init_memory_cache)
    // Set up memory cache
    if (DEBUG) {
        Log.d(TAG, "Memory cache created (size = " + memoryCacheSize + ")");
    }

    // If we're running on Honeycomb or newer, create a set of reusable bitmaps that can be
    // populated into the inBitmap field of BitmapFactory.Options. Note that the set is
    // of SoftReferences which will actually not be very effective due to the garbage
    // collector being aggressive clearing Soft/WeakReferences. A better approach
    // would be to use a strongly references bitmaps, however this would require some
    // balancing of memory usage between this set and the bitmap LruCache. It would also
    // require knowledge of the expected size of the bitmaps. From Honeycomb to JellyBean
    // the size would need to be precise, from KitKat onward the size would just need to
    // be the upper bound (due to changes in how inBitmap can re-use bitmaps).
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        mReusableBitmaps = Collections.synchronizedSet(new HashSet<SoftReference<Bitmap>>());
    }

    mMemoryCache = new LruCache<String, BitmapDrawable>(memoryCacheSize) {

        /**
         * Notify the removed entry that is no longer being cached
         */
        @Override
        protected void entryRemoved(boolean evicted, String key, BitmapDrawable oldValue,
                BitmapDrawable newValue) {
            if (RecyclingBitmapDrawable.class.isInstance(oldValue)) {

                // The removed entry is a recycling drawable, so notify it
                // that it has been removed from the memory cache
                ((RecyclingBitmapDrawable) oldValue).setIsCached(false);
            } else {
                // The removed entry is a standard BitmapDrawable

                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
                    // We're running on Honeycomb or later, so add the bitmap
                    // to a SoftReference set for possible use with inBitmap later
                    mReusableBitmaps.add(new SoftReference<Bitmap>(oldValue.getBitmap()));
                }
            }
        }

        /**
         * Measure item size in kilobytes rather than units which is more practical
         * for a bitmap cache
         */
        @Override
        protected int sizeOf(String key, BitmapDrawable value) {
            final int bitmapSize = getBitmapSize(value) / 1024;
            return bitmapSize == 0 ? 1 : bitmapSize;
        }
    };
    //END_INCLUDE(init_memory_cache)
}

From source file:tw.waterdrop.waterdrop.util.ImageCache.java

/**
 * Initialize the cache, providing all parameters.
 *
 * @param cacheParams The cache parameters to initialize the cache
 *//*from  www  . ja v a 2 s  .c  om*/
private void init(ImageCacheParams cacheParams) {
    mCacheParams = cacheParams;

    //BEGIN_INCLUDE(init_memory_cache)
    // Set up memory cache
    if (mCacheParams.memoryCacheEnabled) {

        // If we're running on Honeycomb or newer, create a set of reusable bitmaps that can be
        // populated into the inBitmap field of BitmapFactory.Options. Note that the set is
        // of SoftReferences which will actually not be very effective due to the garbage
        // collector being aggressive clearing Soft/WeakReferences. A better approach
        // would be to use a strongly references bitmaps, however this would require some
        // balancing of memory usage between this set and the bitmap LruCache. It would also
        // require knowledge of the expected size of the bitmaps. From Honeycomb to JellyBean
        // the size would need to be precise, from KitKat onward the size would just need to
        // be the upper bound (due to changes in how inBitmap can re-use bitmaps).
        if (Utils.hasHoneycomb()) {
            mReusableBitmaps = Collections.synchronizedSet(new HashSet<SoftReference<Bitmap>>());
        }

        mMemoryCache = new LruCache<String, BitmapDrawable>(mCacheParams.memCacheSize) {

            /**
             * Notify the removed entry that is no longer being cached
             */
            @Override
            protected void entryRemoved(boolean evicted, String key, BitmapDrawable oldValue,
                    BitmapDrawable newValue) {

                // The removed entry is a standard BitmapDrawable

                if (Utils.hasHoneycomb()) {
                    // We're running on Honeycomb or later, so add the bitmap
                    // to a SoftReference set for possible use with inBitmap later
                    mReusableBitmaps.add(new SoftReference<Bitmap>(oldValue.getBitmap()));
                }

            }

            /**
             * Measure item size in kilobytes rather than units which is more practical
             * for a bitmap cache
             */
            @Override
            protected int sizeOf(String key, BitmapDrawable value) {
                final int bitmapSize = getBitmapSize(value) / 1024;
                return bitmapSize == 0 ? 1 : bitmapSize;
            }
        };
    }
    //END_INCLUDE(init_memory_cache)

    // By default the disk cache is not initialized here as it should be initialized
    // on a separate thread due to disk access.
    if (cacheParams.initDiskCacheOnCreate) {
        // Set up disk cache
        initDiskCache();
    }
}

From source file:cn.com.wo.bitmap.ImageCache.java

/**
 * Initialize the cache, providing all parameters.
 *
 * @param cacheParams The cache parameters to initialize the cache
 *///from   w  w w .j a  v a  2  s  . c  o m
private void init(ImageCacheParams cacheParams) {
    mCacheParams = cacheParams;

    // Set up memory cache
    if (mCacheParams.memoryCacheEnabled) {
        if (ImageFetcher.isDebug) {
            Log.d(ImageFetcher.TAG,
                    "ImageCache Memory cache created (size = " + mCacheParams.memCacheSize + ")");
        }

        // If we're running on Honeycomb or newer, then
        if (Utils.hasHoneycomb()) {
            mReusableBitmaps = new HashSet<WeakReference<Bitmap>>();
        }

        mMemoryCache = new LruCache<String, WeakReference<BitmapDrawable>>(mCacheParams.memCacheSize) {

            /**
             * Notify the removed entry that is no longer being cached
             */
            @Override
            protected void entryRemoved(boolean evicted, String key, WeakReference<BitmapDrawable> oldValue,
                    WeakReference<BitmapDrawable> newValue) {
                BitmapDrawable drawValue = oldValue.get();
                if (drawValue != null && RecyclingBitmapDrawable.class.isInstance(oldValue)) {
                    ((RecyclingBitmapDrawable) drawValue).setIsCached(false);
                }

                Bitmap bmp = null;
                if (drawValue != null) {
                    bmp = drawValue.getBitmap();
                }
                if (evicted && bmp != null && !bmp.isRecycled()) {
                    //                       bmp.recycle();  
                    bmp = null;
                    drawValue = null;
                }

                //xiaoxh
                //                    if (RecyclingBitmapDrawable.class.isInstance(oldValue)) {
                //                        // The removed entry is a recycling drawable, so notify it 
                //                        // that it has been removed from the memory cache
                ////                        ((RecyclingBitmapDrawable) oldValue).setIsCached(false);
                //                       BitmapDrawable drawValue = oldValue.get();
                //                       if(drawValue != null)
                //                          ((RecyclingBitmapDrawable) drawValue).setIsCached(false);
                ////                       else
                ////                          mMemoryCache.remove(key);
                //                    } else {
                //                        // The removed entry is a standard BitmapDrawable
                //
                //                        if (Utils.hasHoneycomb()) {
                //                            // We're running on Honeycomb or later, so add the bitmap
                //                            // to a SoftRefrence set for possible use with inBitmap later
                //                           BitmapDrawable drawValue = oldValue.get();
                //                           if(drawValue != null)
                //                              mReusableBitmaps.add(new WeakReference<Bitmap>(drawValue.getBitmap()));
                //                        }
                //                    }
            }

            /**
             * Measure item size in kilobytes rather than units which is more practical
             * for a bitmap cache
             */
            @Override
            protected int sizeOf(String key, WeakReference<BitmapDrawable> value) {
                final int bitmapSize = getBitmapSize(value.get()) / 1024;
                return bitmapSize == 0 ? 1 : bitmapSize;
            }
        };
    }

    // By default the disk cache is not initialized here as it should be initialized
    // on a separate thread due to disk access.
    if (cacheParams.initDiskCacheOnCreate) {
        // Set up disk cache
        initDiskCache();
    }
}

From source file:com.itsherpa.andg.imageloader.ImageWorker.java

/**
 * Load an image specified by the data parameter into an ImageView (override
 * {@link ImageWorker#processBitmap(Object)} to define the processing
 * logic). A memory and disk cache will be used if an {@link ImageCache} has
 * been added using//from   w w  w.j  a  v a 2  s  .c  o  m
 * {@link ImageWorker#addImageCache(FragmentManager, ImageCache.ImageCacheParams)}
 * . If the image is found in the memory cache, it is set immediately,
 * otherwise an {@link AsyncTask} will be created to asynchronously load the
 * bitmap.
 * 
 * @param data
 *            The URL of the image to download.
 * @param imageView
 *            The ImageView to bind the downloaded image to.
 */
private void loadImage(Object data, ImageView imageView, int width, int height, int gender, boolean hasCover,
        ImageListener imageListener) {

    if (data == null) {
        return;
    }
    BitmapDrawable value = null;
    if (mImageCache != null) {
        value = mImageCache.getBitmapFromMemCache(getCacheKeyFromObject(data));
    }
    boolean isCircle = false;
    if (data instanceof CircleImageRequest) {
        isCircle = true;
    }
    Bitmap loadingBitmap = getBitmapCover(hasCover, gender, isCircle);

    if (value != null) {
        // Bitmap found in memory cache
        Bitmap bitmap = value.getBitmap();
        if (isCircle) {
            bitmap = Utils.getBitmapInCircle(bitmap);
        }
        imageView.setImageBitmap(bitmap);
        if (imageListener != null)
            imageListener.onGetImageSuccess(value.getBitmap());
    } else if (cancelPotentialWork(data, imageView)) {
        final BitmapWorkerTask task = new BitmapWorkerTask(imageView, width, height, gender, hasCover, isCircle,
                imageListener);

        final AsyncDrawable asyncDrawable = new AsyncDrawable(mResources, loadingBitmap, task);
        imageView.setImageDrawable(asyncDrawable);

        // NOTE: This uses a custom version of AsyncTask that has been
        // pulled from the
        // framework and slightly modified. Refer to the docs at the top of
        // the class
        // for more info on what was changed.
        task.executeOnExecutor(AsyncTask.DUAL_THREAD_EXECUTOR, data);
    }

}

From source file:gr.unfold.android.tsibato.images.ImageCache.java

/** Initialise the cache, providing all parameters. */
private void init(ImageCacheParams cacheParams) {
    mCacheParams = cacheParams;//www  .j a v  a 2 s. c o m

    if (mCacheParams.memoryCacheEnabled) {
        if (AppConfig.DEBUG) {
            Log.d(TAG, "Memory cache created (size = " + mCacheParams.memCacheSize + ")");
        }

        if (Utils.hasHoneycomb()) {
            mReusableBitmaps = new HashSet<SoftReference<Bitmap>>();
        }

        mMemoryCache = new LruCache<String, BitmapDrawable>(mCacheParams.memCacheSize) {
            @Override
            protected void entryRemoved(boolean evicted, String key, BitmapDrawable oldValue,
                    BitmapDrawable newValue) {
                if (RecyclingBitmapDrawable.class.isInstance(oldValue)) {
                    // The removed entry is a recycling drawable, so notify it that it has been removed from the memory cache
                    ((RecyclingBitmapDrawable) oldValue).setIsCached(false);
                } else {
                    // The removed entry is a standard BitmapDrawable
                    if (Utils.hasHoneycomb()) {
                        // We're running on Honeycomb or later, so add the bitmap to a SoftRefrence set for possible use with inBitmap later
                        mReusableBitmaps.add(new SoftReference<Bitmap>(oldValue.getBitmap()));
                    }
                }
            }

            @Override
            protected int sizeOf(String key, BitmapDrawable value) {
                final int bitmapSize = getBitmapSize(value) / 1024;
                return bitmapSize == 0 ? 1 : bitmapSize;
            }
        };
    }

    if (cacheParams.initDiskCacheOnCreate) {
        initDiskCache();
    }
}

From source file:ch.dbrgn.android.simplerepost.activities.RepostActivity.java

/**
 * Add the watermark from the specified resource file onto the
 * specified image.//  w  ww.  j  a va  2s . c o  m
 */
private Bitmap addWatermark(String filename, int watermarkResourceFile) {
    // Read background into drawable
    BitmapDrawable background = null;
    try {
        final InputStream is = openFileInput(filename);
        background = new BitmapDrawable(getResources(), is);
        is.close();
    } catch (FileNotFoundException e) {
        ToastHelper.showShortToast(this, "Could not find downloaded image on filesystem");
        Log.e(LOG_TAG, "IOException: " + e.toString());
        return null;
    } catch (IOException e) {
        Log.w(LOG_TAG, "Could not close InputStream");
    }

    // Read watermark into Drawable
    final InputStream is = getResources().openRawResource(watermarkResourceFile);
    final BitmapDrawable watermark = new BitmapDrawable(getResources(), is);
    try {
        is.close();
    } catch (IOException e) {
        Log.w(LOG_TAG, "Could not close InputStream");
    }

    // Get dimensions
    int w = background.getBitmap().getWidth();
    int h = background.getBitmap().getHeight();

    // Create canvas for final output
    Bitmap watermarked = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(watermarked);

    // Write background onto canvas
    background.setBounds(0, 0, w, h);
    background.draw(canvas);
    background.getBitmap().recycle();

    // Write watermark onto canvas
    watermark.setBounds(0, 0, w, h);
    watermark.draw(canvas);
    watermark.getBitmap().recycle();

    return watermarked;
}

From source file:de.vanita5.twittnuker.view.ShapedImageView.java

@Override
protected void onDraw(@NonNull Canvas canvas) {

    mDestination.set(getPaddingLeft(), getPaddingTop(), getWidth() - getPaddingRight(),
            getHeight() - getPaddingBottom());

    if (getStyle() == SHAPE_CIRCLE) {
        canvas.drawOval(mDestination, mBackgroundPaint);
    } else {//from   www.  ja  v  a 2s .  c  o  m
        final float radius = getCalculatedCornerRadius();
        canvas.drawRoundRect(mDestination, radius, radius, mBackgroundPaint);
    }

    if (OUTLINE_DRAW) {
        super.onDraw(canvas);
    } else {
        final int contentLeft = getPaddingLeft(), contentTop = getPaddingTop(),
                contentRight = getWidth() - getPaddingRight(), contentBottom = getHeight() - getPaddingBottom();
        final int contentWidth = contentRight - contentLeft, contentHeight = contentBottom - contentTop;
        final int size = Math.min(contentWidth, contentHeight);
        if (mShadowBitmap != null) {
            canvas.drawBitmap(mShadowBitmap, contentLeft + (contentWidth - size) / 2 - mShadowRadius,
                    contentTop + (contentHeight - size) / 2 - mShadowRadius, null);
        }
        Drawable drawable = getDrawable();
        BitmapDrawable bitmapDrawable = null;
        // support state list drawable by getting the current state
        if (drawable instanceof StateListDrawable) {
            if (drawable.getCurrent() != null) {
                bitmapDrawable = (BitmapDrawable) drawable.getCurrent();
            }
        } else if (drawable instanceof BitmapDrawable) {
            bitmapDrawable = (BitmapDrawable) drawable;
        } else if (drawable instanceof ColorDrawable) {
            mSolidColorPaint.setColor(((ColorDrawable) drawable).getColor());
        } else {
            mSolidColorPaint.setColor(0);
        }

        Bitmap bitmap = null;
        if (bitmapDrawable != null) {
            bitmap = bitmapDrawable.getBitmap();
        }
        if (bitmap != null) {
            mSource.set(0, 0, bitmap.getWidth(), bitmap.getHeight());
        }
        drawBitmapWithCircleOnCanvas(bitmap, canvas, mSource, mDestination);
    }

    // Then draw the border.
    if (mBorderEnabled) {
        drawBorder(canvas);
    }
}

From source file:com.example.android.foodrecipes.app.RecipeDetailsFragment.java

private void saveCurrentRecipeInFavorites() {
    String title = getActivity().getString(R.string.text_please_wait);
    String text = getActivity().getString(R.string.text_saving_in_favorites);

    final ProgressDialog dialog = ProgressDialog.show(getActivity(), title, text);
    final BitmapDrawable bitmapDrawable = (BitmapDrawable) mRecipeImage.getDrawable();

    dialog.show();/*from ww w  .j  av a2s. co  m*/

    final AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
        @Override
        protected Void doInBackground(Void... params) {
            ContentValues cv = new ContentValues();
            cv.put(COLUMN_EXTERNAL_ID, mRecipe.getExternalId());
            cv.put(COLUMN_TITLE, mRecipe.getTitle());
            cv.put(COLUMN_IMAGE_URL, mRecipe.getImageUrl());
            cv.put(COLUMN_SOCIAL_RANK, mRecipe.getSocialRank());
            cv.put(COLUMN_SOURCE_URL, mRecipe.getSourceUrl());
            cv.put(COLUMN_INGREDIENTS, buildIngredientsString(mRecipe.getIngredients()));

            if (PrefsUtil.shouldSaveRecipeImages(getActivity())) {
                Bitmap bitmap = bitmapDrawable.getBitmap();
                if (bitmap != null) {
                    ByteArrayOutputStream stream = new ByteArrayOutputStream();
                    bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
                    cv.put(COLUMN_IMAGE_CONTENT, stream.toByteArray());
                }
            }

            getActivity().getContentResolver().insert(CONTENT_URI, cv);

            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            dialog.dismiss();
            Toast.makeText(getActivity(), getActivity().getString(R.string.recipe_saved_in_favorites),
                    Toast.LENGTH_SHORT).show();

            mFavoritesActionButton.setEnabled(false);
        }
    };

    dialog.setOnKeyListener(new Dialog.OnKeyListener() {
        @Override
        public boolean onKey(DialogInterface dialogInterface, int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_BACK) {
                task.cancel(true);
                dialog.dismiss();
            }
            return true;
        }
    });

    task.execute();
}