Example usage for android.graphics Bitmap recycle

List of usage examples for android.graphics Bitmap recycle

Introduction

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

Prototype

public void recycle() 

Source Link

Document

Free the native object associated with this bitmap, and clear the reference to the pixel data.

Usage

From source file:Main.java

/**
 * Load the image at {@code imagePath} as a {@link Bitmap}, scaling it to
 * the specified size and preserving the aspect ratio.
 * @param imagePath Path of the image to load.
 * @param width Required width of the resulting {@link Bitmap}.
 * @param height Required height of the resulting {@link Bitmap}.
 * @param fill {@code true} to fill the empty space with transparent color.
 * @param crop {@code true} to crop the image, {@code false} to resize without cutting the image.
 * @return {@link Bitmap} representing the image at {@code imagePath}.
 *//*  w ww.j  a v  a  2 s. c o  m*/
public static Bitmap loadResizedBitmap(String imagePath, int width, int height, boolean fill, boolean crop) {
    Bitmap retVal;

    BitmapFactory.Options opts = new BitmapFactory.Options();
    opts.inSampleSize = getScale(imagePath, width, height);
    opts.inJustDecodeBounds = false;

    Bitmap image = BitmapFactory.decodeFile(imagePath, opts);

    if (image == null) {
        return null;
    }

    if (image.getWidth() != width || image.getHeight() != height) {
        //Image need to be resized.
        //         int scaledWidth = image.getWidth();
        //         int scaledHeight = image.getHeight();
        //         final float factorWidth = scaledWidth / width;
        //         final float factorHeight = scaledHeight / height;
        //final float factor = (scaledWidth / width) - (scaledHeight / height);
        //         final long factor = (scaledWidth * height) - (scaledHeight * width);
        //         if ((crop && factor > 0) || (factor < 0)) {
        //            scaledHeight = (scaledHeight * width) / scaledWidth;
        //            scaledWidth = width;
        //         } else {
        //            scaledWidth = (scaledWidth * height) / scaledHeight;
        //            scaledHeight = height;
        //         }
        int scaledWidth = (image.getWidth() * height) / image.getHeight();
        int scaledHeight; // = (image.getHeight() * width) / image.getWidth();
        if ((crop && scaledWidth > width) || (!crop && scaledWidth < width)) {
            scaledHeight = height;
        } else {
            scaledWidth = width;
            scaledHeight = (image.getHeight() * width) / image.getWidth();
        }
        //image = Bitmap.createScaledBitmap(image, scaledWidth, scaledHeight, true);

        Rect src = new Rect(0, 0, image.getWidth(), image.getHeight());
        Rect dst = new Rect(0, 0, scaledWidth, scaledHeight);

        if (fill) {
            retVal = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
            dst.offset((width - scaledWidth) / 2, (height - scaledHeight) / 2);
        } else {
            retVal = Bitmap.createBitmap(scaledWidth, scaledHeight, Bitmap.Config.ARGB_8888);
        }
        retVal.eraseColor(Color.TRANSPARENT);

        synchronized (canvas) {
            if (antiAliasPaint == null) {
                antiAliasPaint = new Paint();
                antiAliasPaint.setAntiAlias(true);
                antiAliasPaint.setFilterBitmap(true);
                antiAliasPaint.setDither(true);
            }
            canvas.setBitmap(retVal);
            canvas.drawBitmap(image, src, dst, antiAliasPaint);
        }

        image.recycle();
    } else {
        //No need to scale.
        retVal = image;
    }

    return retVal;
}

From source file:com.gfan.sbbs.utils.images.ImageManager.java

/**
 * Bitmap//w w w.j ava 2 s . com
 * 
 * @param bitmap
 * @param maxWidth
 * @param maxHeight
 * @param quality
 *            1~100
 * @return
 */
public Bitmap resizeBitmap(Bitmap bitmap, int maxWidth, int maxHeight) {
    Log.i(TAG, "resizing a bitmap");
    if (null == bitmap) {
        return null;
    }
    int originWidth = bitmap.getWidth();
    int originHeight = bitmap.getHeight();

    // no need to resize
    if (originWidth < maxWidth && originHeight < maxHeight) {
        return bitmap;
    }

    int newWidth = originWidth;
    int newHeight = originHeight;
    Bitmap newBitmap = null;

    // , 
    if (originWidth > maxWidth) {
        newWidth = maxWidth;

        double i = originWidth * 1.0 / maxWidth;
        newHeight = (int) Math.floor(originHeight / i);

        newBitmap = Bitmap.createScaledBitmap(bitmap, newWidth, newHeight, true);
    }

    // , 
    if (newHeight > maxHeight) {
        newHeight = maxHeight;

        int half_diff = (int) ((originHeight - maxHeight) / 2.0);
        newBitmap = Bitmap.createBitmap(bitmap, 0, half_diff, newWidth, newHeight);
    }

    bitmap.recycle();
    Log.d(TAG, newWidth + " width");
    Log.d(TAG, newHeight + " height");

    return newBitmap;
}

From source file:com.ibuildapp.romanblack.FanWallPlugin.data.Statics.java

/**
 * Sets the downloaded attached image.//ww w  .j ava 2 s .  com
 *
 * @param fileName picture file path
 */
public static Bitmap publishPicture(String fileName) {
    Bitmap bitmap = null;
    try {

        if (!TextUtils.isEmpty(fileName)) {
            try {
                BitmapFactory.Options opts = new BitmapFactory.Options();
                opts.inJustDecodeBounds = true;
                BitmapFactory.decodeFile(fileName, opts);

                //Find the correct scale value. It should be the power of 2.
                int width = opts.outWidth, height = opts.outHeight;
                int scale = 1;
                while (true) {
                    if (width / 2 <= 150 || height / 2 <= 150) {
                        break;
                    }
                    width /= 2;
                    height /= 2;
                    scale *= 2;
                }
                BitmapFactory.Options opt = new BitmapFactory.Options();
                opt.inSampleSize = scale;

                bitmap = BitmapFactory.decodeFile(fileName, opt);
                int size = 0;
                if (bitmap.getHeight() > bitmap.getWidth()) {
                    size = bitmap.getWidth();
                } else {
                    size = bitmap.getHeight();
                }
                Bitmap output = Bitmap.createBitmap(size, size, Bitmap.Config.RGB_565);
                Canvas canvas = new Canvas(output);

                final int color = 0xff424242;
                final Paint paint = new Paint();
                final Rect rect = new Rect(0, 0, size, size);
                final RectF rectF = new RectF(rect);
                final float roundPx = 0;

                paint.setAntiAlias(true);
                canvas.drawARGB(0, 0, 0, 0);
                paint.setColor(color);
                canvas.drawRoundRect(rectF, roundPx, roundPx, paint);

                paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
                canvas.drawBitmap(bitmap, rect, rect, paint);

                bitmap.recycle();

                return output;
            } catch (Exception e) {
                Log.w("", "");
            }
        }
    } catch (Exception ex) {

    }

    return null;
}

From source file:com.miz.functions.MizLib.java

public static void resizeBitmapFileToCoverSize(Context c, String filepath) {

    final int mImageThumbSize = c.getResources().getDimensionPixelSize(R.dimen.image_thumbnail_size);
    final int mImageThumbSpacing = c.getResources().getDimensionPixelSize(R.dimen.image_thumbnail_spacing);

    WindowManager window = (WindowManager) c.getSystemService(Context.WINDOW_SERVICE);
    Display d = window.getDefaultDisplay();

    Point size = new Point();
    d.getSize(size);/*from   w  w w . ja v  a2s .  c  o m*/

    final int numColumns = (int) Math.floor(Math.max(size.x, size.y) / (mImageThumbSize + mImageThumbSpacing));

    if (numColumns > 0) {
        final int columnWidth = (Math.max(size.x, size.y) / numColumns) - mImageThumbSpacing;

        int imageWidth = 0;

        if (columnWidth > 300)
            imageWidth = 500;
        else if (columnWidth > 240)
            imageWidth = 320;
        else if (columnWidth > 180)
            imageWidth = 240;
        else
            imageWidth = 180;

        if (new File(filepath).exists())
            try {
                Bitmap bm = decodeSampledBitmapFromFile(filepath, imageWidth, (int) (imageWidth * 1.5));
                bm = Bitmap.createScaledBitmap(bm, imageWidth, (int) (imageWidth * 1.5), true);
                FileOutputStream out = new FileOutputStream(filepath);
                bm.compress(Bitmap.CompressFormat.JPEG, 90, out);
                out.close();
                bm.recycle();
            } catch (Exception e) {
            }
    }
}

From source file:cn.finalteam.galleryfinal.PhotoEditActivity.java

/**
 * /*from   w  w w  . j  a va2s  . com*/
 */
private void rotatePhoto() {
    if (mPhotoList.size() > 0 && mPhotoList.get(mSelectIndex) != null && !mRotating) {
        final PhotoInfo photoInfo = mPhotoList.get(mSelectIndex);
        final String ext = FilenameUtils.getExtension(photoInfo.getPhotoPath());
        if (StringUtils.isEmpty(ext) || !(ext.equalsIgnoreCase("png") || ext.equalsIgnoreCase("jpg")
                || ext.equalsIgnoreCase("jpeg"))) {
            toast(getString(R.string.edit_letoff_photo_format));
            return;
        }
        mRotating = true;
        if (photoInfo != null) {
            final PhotoTempModel photoTempModel = mPhotoTempMap.get(photoInfo.getPhotoId());
            final String path = photoTempModel.getSourcePath();

            File file;
            if (GalleryFinal.getFunctionConfig().isRotateReplaceSource()) { //??
                file = new File(path);
            } else {
                file = new File(mEditPhotoCacheFile, Utils.getFileName(path) + "_rotate." + ext);
            }

            final File rotateFile = file;
            new AsyncTask<Void, Void, Bitmap>() {
                @Override
                protected void onPreExecute() {
                    super.onPreExecute();
                    mTvEmptyView.setVisibility(View.VISIBLE);
                    mProgressDialog = ProgressDialog.show(PhotoEditActivity.this, "",
                            getString(R.string.waiting), true, false);
                }

                @Override
                protected Bitmap doInBackground(Void... params) {
                    int orientation;
                    if (GalleryFinal.getFunctionConfig().isRotateReplaceSource()) {
                        orientation = 90;
                    } else {
                        orientation = photoTempModel.getOrientation() + 90;
                    }
                    Bitmap bitmap = Utils.rotateBitmap(path, orientation, mScreenWidth, mScreenHeight);
                    if (bitmap != null) {
                        Bitmap.CompressFormat format;
                        if (ext.equalsIgnoreCase("jpg") || ext.equalsIgnoreCase("jpeg")) {
                            format = Bitmap.CompressFormat.JPEG;
                        } else {
                            format = Bitmap.CompressFormat.PNG;
                        }
                        Utils.saveBitmap(bitmap, format, rotateFile);
                    }
                    return bitmap;
                }

                @Override
                protected void onPostExecute(Bitmap bitmap) {
                    super.onPostExecute(bitmap);
                    if (mProgressDialog != null) {
                        mProgressDialog.dismiss();
                        mProgressDialog = null;
                    }
                    if (bitmap != null) {
                        bitmap.recycle();

                        mTvEmptyView.setVisibility(View.GONE);

                        if (!GalleryFinal.getFunctionConfig().isRotateReplaceSource()) {
                            int orientation = photoTempModel.getOrientation() + 90;
                            if (orientation == 360) {
                                orientation = 0;
                            }
                            photoTempModel.setOrientation(orientation);
                        }

                        Message message = mHanlder.obtainMessage();
                        message.what = UPDATE_PATH;
                        message.obj = rotateFile.getAbsolutePath();
                        mHanlder.sendMessage(message);
                    } else {
                        mTvEmptyView.setText(R.string.no_photo);
                    }
                    loadImage(photoInfo);
                    mRotating = false;
                }
            }.execute();
        }
    }
}

From source file:ir.rasen.charsoo.controller.image_loader.core.decode.BaseImageDecoder.java

protected Bitmap considerExactScaleAndOrientatiton(Bitmap subsampledBitmap, ImageDecodingInfo decodingInfo,
        int rotation, boolean flipHorizontal) {
    Matrix m = new Matrix();
    // Scale to exact size if need
    ImageScaleType scaleType = decodingInfo.getImageScaleType();
    if (scaleType == ImageScaleType.EXACTLY || scaleType == ImageScaleType.EXACTLY_STRETCHED) {
        ImageSize srcSize = new ImageSize(subsampledBitmap.getWidth(), subsampledBitmap.getHeight(), rotation);
        float scale = ImageSizeUtils.computeImageScale(srcSize, decodingInfo.getTargetSize(),
                decodingInfo.getViewScaleType(), scaleType == ImageScaleType.EXACTLY_STRETCHED);
        if (Float.compare(scale, 1f) != 0) {
            m.setScale(scale, scale);// w  w  w  .  j  av  a 2  s  . c  o m

            if (loggingEnabled) {
                L.d(LOG_SCALE_IMAGE, srcSize, srcSize.scale(scale), scale, decodingInfo.getImageKey());
            }
        }
    }
    // Flip bitmap if need
    if (flipHorizontal) {
        m.postScale(-1, 1);

        if (loggingEnabled)
            L.d(LOG_FLIP_IMAGE, decodingInfo.getImageKey());
    }
    // Rotate bitmap if need
    if (rotation != 0) {
        m.postRotate(rotation);

        if (loggingEnabled)
            L.d(LOG_ROTATE_IMAGE, rotation, decodingInfo.getImageKey());
    }

    Bitmap finalBitmap = Bitmap.createBitmap(subsampledBitmap, 0, 0, subsampledBitmap.getWidth(),
            subsampledBitmap.getHeight(), m, true);
    if (finalBitmap != subsampledBitmap) {
        subsampledBitmap.recycle();
    }
    return finalBitmap;
}

From source file:com.ktouch.kdc.launcher4.camera.CameraManager.java

/**
 * Returns the last frame of the preview surface
 *
 * @return Bitmap//  w w  w  .j a  v a2s.c om
 */
public Bitmap getLastPreviewFrame() {
    // Decode the last frame bytes
    byte[] data = mPreview.getLastFrameBytes();
    Camera.Parameters params = getParameters();

    if (params == null) {
        return null;
    }

    Camera.Size previewSize = params.getPreviewSize();
    if (previewSize == null) {
        return null;
    }

    int previewWidth = previewSize.width;
    int previewHeight = previewSize.height;

    // Convert YUV420SP preview data to RGB
    try {
        if (data != null && data.length > 8) {
            Bitmap bitmap = Util.decodeYUV420SP(mContext, data, previewWidth, previewHeight);
            if (mCurrentFacing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
                // Frontcam has the image flipped, flip it back to not look weird in portrait
                Matrix m = new Matrix();
                m.preScale(-1, 1);
                Bitmap dst = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), m, false);
                bitmap.recycle();
                bitmap = dst;
            }

            return bitmap;
        } else {
            return null;
        }
    } catch (ArrayIndexOutOfBoundsException e) {
        // TODO: FIXME: On some devices, the resolution of the preview might abruptly change,
        // thus the YUV420SP data is not the size we expect, causing OOB exception
        return null;
    }
}

From source file:com.xmobileapp.rockplayer.LastFmAlbumArtImporter.java

/*********************************
 * /*w ww  .j a  v a  2s . c  o m*/
 * creatAlbumArt
 * 
 *********************************/
public Bitmap createAlbumArt(String artistName, String albumName, Bitmap bm) {
    String fileName = ((RockPlayer) context).FILEX_ALBUM_ART_PATH + validateFileName(artistName) + " - "
            + validateFileName(albumName) + FILEX_FILENAME_EXTENSION;
    validateFileName(fileName);
    File albumArtFile = new File(fileName);

    try {
        /*
         * Set file output
         */

        albumArtFile.createNewFile();
        FileOutputStream albumArtFileStream = new FileOutputStream(albumArtFile);

        /*
          * Rescale/Crop the Bitmap
          */
        int MAX_SIZE = 480;
        float scaleFactor = (float) Math.max(1.0f,
                Math.min((float) bm.getWidth() / (float) MAX_SIZE, (float) bm.getHeight() / (float) MAX_SIZE));
        Log.i("CREATE", "" + scaleFactor);
        Bitmap albumArtBitmap = Bitmap.createScaledBitmap(bm,
                (int) Math.round((float) bm.getWidth() / scaleFactor),
                (int) Math.round((float) bm.getHeight() / scaleFactor), false);

        if (albumArtBitmap != null) {
            int dimension = Math.min(480, Math.min(albumArtBitmap.getHeight(), albumArtBitmap.getWidth()));
            Bitmap albumArtBitmapRescaled = Bitmap.createBitmap(albumArtBitmap,
                    (int) Math.floor((albumArtBitmap.getWidth() - dimension) / 2),
                    (int) Math.floor((albumArtBitmap.getHeight() - dimension) / 2), (int) dimension,
                    (int) dimension);

            FileOutputStream rescaledAlbumArtFileStream;
            rescaledAlbumArtFileStream = new FileOutputStream(albumArtFile);
            albumArtBitmapRescaled.compress(Bitmap.CompressFormat.JPEG, 96, rescaledAlbumArtFileStream);
            rescaledAlbumArtFileStream.close();
            if (albumArtBitmapRescaled != null)
                albumArtBitmapRescaled.recycle();

        } else {
            albumArtFile.delete();
        }
        if (albumArtBitmap != null)
            albumArtBitmap.recycle();
        return albumArtBitmap;
    } catch (Exception e) {
        e.printStackTrace();
        albumArtFile.delete();
        return null;
    } catch (Error err) {
        err.printStackTrace();
        return null;
    }

}

From source file:com.prt.thirdeye.CamManager.java

/**
 * Returns the last frame of the preview surface
 * /* ww  w  .  ja  va 2s. c om*/
 * @return Bitmap
 */
public Bitmap getLastPreviewFrame() {
    // Decode the last frame bytes
    byte[] data = mPreview.getLastFrameBytes();
    Camera.Parameters params = getParameters();

    if (params == null) {
        return null;
    }

    Camera.Size previewSize = params.getPreviewSize();
    if (previewSize == null) {
        return null;
    }

    int previewWidth = previewSize.width;
    int previewHeight = previewSize.height;

    // Convert YUV420SP preview data to RGB
    try {
        if (data != null && data.length > 8) {
            Bitmap bitmap = Util.decodeYUV420SP(mContext, data, previewWidth, previewHeight);
            if (mCurrentFacing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
                // Frontcam has the image flipped, flip it back to not look
                // weird in portrait
                Matrix m = new Matrix();
                m.preScale(-1, 1);
                Bitmap dst = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), m, false);
                bitmap.recycle();
                bitmap = dst;
            }

            return bitmap;
        } else {
            return null;
        }
    } catch (ArrayIndexOutOfBoundsException e) {
        // TODO: FIXME: On some devices, the resolution of the preview might
        // abruptly change,
        // thus the YUV420SP data is not the size we expect, causing OOB
        // exception
        return null;
    }
}

From source file:com.gelakinetic.mtgfam.fragments.CardViewFragment.java

/**
 * Release all image resources and invoke the garbage collector
 *///from ww  w  .  j  ava2 s.c  om
private void releaseImageResources(boolean isSplit) {

    if (mCardImageView != null) {

        /* Release the drawable from the ImageView */
        Drawable drawable = mCardImageView.getDrawable();
        if (drawable != null) {
            drawable.setCallback(null);
            Bitmap drawableBitmap = ((BitmapDrawable) drawable).getBitmap();
            if (drawableBitmap != null) {
                drawableBitmap.recycle();
            }
        }

        /* Release the ImageView */
        mCardImageView.setImageDrawable(null);
        mCardImageView.setImageBitmap(null);

        if (!isSplit) {
            mCardImageView = null;
        }
    }
    if (mCardBitmap != null) {
        /* Release the drawable */
        mCardBitmap.getBitmap().recycle();
        mCardBitmap = null;
    }

    if (!isSplit) {
        mNameTextView = null;
        mCostTextView = null;
        mTypeTextView = null;
        mSetTextView = null;
        mAbilityTextView = null;
        mFlavorTextView = null;
        mArtistTextView = null;
        mNumberTextView = null;
        mPowTouTextView = null;
        mTransformButtonDivider = null;
        mTransformButton = null;
        mTextScrollView = null;
        mImageScrollView = null;
        mCardImageView = null;
        mColorIndicatorLayout = null;
    }

    /* Invoke the garbage collector */
    java.lang.System.gc();
}