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:com.futurologeek.smartcrossing.crop.CropImageActivity.java

private void setupViews() {
    setContentView(R.layout.crop__activity_crop);
    wholeRelative = (RelativeLayout) findViewById(R.id.whole_relative);

    imageView = (CropImageView) findViewById(R.id.crop_image);
    imageView.context = this;
    imageView.setRecycler(new ImageViewTouchBase.Recycler() {
        @Override//  w w w. j  av a2  s.co  m
        public void recycle(Bitmap b) {
            b.recycle();
            System.gc();
        }
    });

    findViewById(R.id.btn_cancel).setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            setResult(RESULT_CANCELED);
            finish();
        }
    });

    findViewById(R.id.btn_done).setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            onSaveClicked();
        }
    });
}

From source file:com.aimfire.gallery.service.PhotoProcessor.java

private void saveThumbnail(String sbsPath, String thumbPath) {
    try {/*w  ww. j  av a2 s  .c  o  m*/
        BitmapRegionDecoder decoder = null;
        Bitmap bmp = null;

        decoder = BitmapRegionDecoder.newInstance(sbsPath, false);
        bmp = decoder.decodeRegion(new Rect(0, 0, decoder.getWidth() / 2, decoder.getHeight()), null);

        Bitmap thumb = ThumbnailUtils.extractThumbnail(bmp, MainConsts.THUMBNAIL_SIZE,
                MainConsts.THUMBNAIL_SIZE);

        FileOutputStream fos;
        fos = new FileOutputStream(thumbPath);
        thumb.compress(CompressFormat.JPEG, 50, fos);
        fos.close();

        if (bmp != null) {
            bmp.recycle();
        }

        if (thumb != null) {
            thumb.recycle();
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

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

/**
 * Source:/*from  w  ww  .  java 2s  .  c  o  m*/
 * 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;
}

From source file:com.gmail.jiangyang5157.cardboard.net.DescriptionRequest.java

/**
 * The real guts of parseNetworkResponse. Broken out for readability.
 *//*from   w ww .j a  va 2 s . co  m*/
private Response<Object> doBitmapParse(NetworkResponse response) {
    byte[] data = response.data;
    BitmapFactory.Options decodeOptions = new BitmapFactory.Options();
    Bitmap bitmap;
    if (mMaxWidth == 0 && mMaxHeight == 0) {
        decodeOptions.inPreferredConfig = mDecodeConfig;
        bitmap = BitmapFactory.decodeByteArray(data, 0, data.length, decodeOptions);
    } else {
        // If we have to resize this image, first get the natural bounds.
        decodeOptions.inJustDecodeBounds = true;
        BitmapFactory.decodeByteArray(data, 0, data.length, decodeOptions);
        int actualWidth = decodeOptions.outWidth;
        int actualHeight = decodeOptions.outHeight;

        // Then compute the dimensions we would ideally like to decode to.
        int desiredWidth = getResizedDimension(mMaxWidth, mMaxHeight, actualWidth, actualHeight, mScaleType);
        int desiredHeight = getResizedDimension(mMaxHeight, mMaxWidth, actualHeight, actualWidth, mScaleType);

        // Decode to the nearest power of two scaling factor.
        decodeOptions.inJustDecodeBounds = false;
        decodeOptions.inSampleSize = findBestSampleSize(actualWidth, actualHeight, desiredWidth, desiredHeight);
        Bitmap tempBitmap = BitmapFactory.decodeByteArray(data, 0, data.length, decodeOptions);

        // If necessary, scale down to the maximal acceptable size.
        if (tempBitmap != null
                && (tempBitmap.getWidth() > desiredWidth || tempBitmap.getHeight() > desiredHeight)) {
            bitmap = Bitmap.createScaledBitmap(tempBitmap, desiredWidth, desiredHeight, true);
            tempBitmap.recycle();
        } else {
            bitmap = tempBitmap;
        }
    }

    if (bitmap == null) {
        return Response.error(new ParseError(response));
    } else {
        return Response.success(bitmap, HttpHeaderParser.parseCacheHeaders(response));
    }
}

From source file:com.android.andryyu.lifehelper.widget.RippleView.java

private void doRippleWork(Canvas canvas, int offect) {
    canvas.save();/*ww  w  . j av  a 2s .  co m*/
    if (rippleDuration <= timer * frameRate) {
        // There is problem on Android M where canvas.restore() seems to be called automatically
        // For now, don't call canvas.restore() manually on Android M (API 23)
        canvas.drawCircle(x, y, (radiusMax * (((float) timer * frameRate) / rippleDuration)), paint);

        if (onCompletionListener != null && rippleStatus != RIPPLE_ACTION_MOVE
                && rippleStatus != RIPPLE_LONG_PRESS) {
            onCompletionListener.onComplete(this);
        }
        if (rippleStatus != RIPPLE_LONG_PRESS) {
            animationRunning = false;
            rippleStatus = RIPPLE_NORMAL;
            timer = 0;
            durationEmpty = -1;
            timerEmpty = 0;
            if (Build.VERSION.SDK_INT != 23) {
                canvas.restore();
            }
        }
        invalidate();
        return;
    } else
        canvasHandler.postDelayed(runnable, frameRate);

    if (timer == 0)
        canvas.save();

    canvas.drawCircle(x, y, (radiusMax * (((float) timer * frameRate) / rippleDuration)), paint);

    paint.setColor(Color.parseColor("#ffff4444"));

    if (rippleType == 1 && originBitmap != null && (((float) timer * frameRate) / rippleDuration) > 0.4f) {
        if (durationEmpty == -1)
            durationEmpty = rippleDuration - timer * frameRate;

        timerEmpty++;
        final Bitmap tmpBitmap = getCircleBitmap(
                (int) ((radiusMax) * (((float) timerEmpty * frameRate) / (durationEmpty))));
        canvas.drawBitmap(tmpBitmap, 0, 0, paint);
        tmpBitmap.recycle();
    }

    paint.setColor(rippleColor);
    if (!isListMode) {
        if (rippleType == 1) {
            if ((((float) timer * frameRate) / rippleDuration) > 0.6f)
                paint.setAlpha((int) (rippleAlpha
                        - ((rippleAlpha) * (((float) timerEmpty * frameRate) / (durationEmpty)))));
            else
                paint.setAlpha(rippleAlpha);
        } else
            paint.setAlpha(
                    (int) (rippleAlpha - ((rippleAlpha) * (((float) timer * frameRate) / rippleDuration))));
    }
    timer += offect;
}

From source file:Main.java

public static Bitmap rotateImage(Bitmap bitmap, String storagePath) {
    Bitmap resultBitmap = bitmap;//  w  ww.jav a 2 s.c o m
    try {
        ExifInterface exifInterface = new ExifInterface(storagePath);
        int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, 1);

        Matrix matrix = new Matrix();

        // 1: nothing to do

        // 2
        if (orientation == ExifInterface.ORIENTATION_FLIP_HORIZONTAL) {
            matrix.postScale(-1.0f, 1.0f);
        }
        // 3
        else if (orientation == ExifInterface.ORIENTATION_ROTATE_180) {
            matrix.postRotate(180);
        }
        // 4
        else if (orientation == ExifInterface.ORIENTATION_FLIP_VERTICAL) {
            matrix.postScale(1.0f, -1.0f);
        }
        // 5
        else if (orientation == ExifInterface.ORIENTATION_TRANSPOSE) {
            matrix.postRotate(-90);
            matrix.postScale(1.0f, -1.0f);
        }
        // 6
        else if (orientation == ExifInterface.ORIENTATION_ROTATE_90) {
            matrix.postRotate(90);
        }
        // 7
        else if (orientation == ExifInterface.ORIENTATION_TRANSVERSE) {
            matrix.postRotate(90);
            matrix.postScale(1.0f, -1.0f);
        }
        // 8
        else if (orientation == ExifInterface.ORIENTATION_ROTATE_270) {
            matrix.postRotate(270);
        }

        // Rotate the bitmap
        resultBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
        if (resultBitmap != bitmap) {
            bitmap.recycle();
        }
    } catch (Exception exception) {
        Log.e("BitmapUtil", "Could not rotate the image: " + storagePath);
    }
    return resultBitmap;
}

From source file:Main.java

public static Bitmap toRoundBitmap(Bitmap bitmap) {
    if (bitmap == null) {
        return null;
    }//w ww.  j  a va2  s. co m
    int width = bitmap.getWidth();
    int height = bitmap.getHeight();
    float roundPx;
    float left, top, right, bottom, dst_left, dst_top, dst_right, dst_bottom;
    if (width <= height) {
        roundPx = width / 2;
        top = 0;
        bottom = width;
        left = 0;
        right = width;
        height = width;
        dst_left = 0;
        dst_top = 0;
        dst_right = width;
        dst_bottom = width;
    } else {
        roundPx = height / 2;
        float clip = (width - height) / 2;
        left = clip;
        right = width - clip;
        top = 0;
        bottom = height;
        width = height;
        dst_left = 0;
        dst_top = 0;
        dst_right = height;
        dst_bottom = height;
    }
    Bitmap output = Bitmap.createBitmap(width, height, Config.ARGB_8888);
    Canvas canvas = new Canvas(output);
    final int color = 0xff424242;
    final Paint paint = new Paint();
    final Rect src = new Rect((int) left, (int) top, (int) right, (int) bottom);
    final Rect dst = new Rect((int) dst_left, (int) dst_top, (int) dst_right, (int) dst_bottom);
    final RectF rectF = new RectF(dst);
    paint.setAntiAlias(true);
    canvas.drawARGB(0, 0, 0, 0);
    paint.setColor(color);
    canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
    paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
    canvas.drawBitmap(bitmap, src, dst, paint);

    if (null != bitmap) {
        bitmap.recycle();
        bitmap = null;
    }
    return output;
}

From source file:com.adrguides.model.Guide.java

private void saveBitmapToFile(Context context, File f, URL imageURL) throws IOException {

    InputStream in = null;/*from  w  ww  .j ava2s.  c om*/
    OutputStream out = null;
    try {

        Bitmap newbmp;

        // read bitmap from source.
        in = HTTPUtils.openAddress(context, imageURL);
        Bitmap bmp = BitmapFactory.decodeStream(in);
        int w = bmp.getWidth();
        int h = bmp.getHeight();
        if (w > h) {
            newbmp = Bitmap.createBitmap(bmp, (w - h) / 2, 0, h, h);
        } else {
            newbmp = Bitmap.createBitmap(bmp, 0, (h - w) / 2, w, w);
        }
        if (newbmp != bmp) {
            bmp.recycle();
            bmp = newbmp;
        }

        float density = context.getResources().getDisplayMetrics().density;
        newbmp = Bitmap.createScaledBitmap(bmp, (int) (THUMBNAIL_WIDTH * density),
                (int) (THUMBNAIL_HEIGHT * density), true);
        if (newbmp != bmp) {
            bmp.recycle();
            bmp = newbmp;
        }

        // store in local filesystem.
        out = new FileOutputStream(f);
        bmp.compress(Bitmap.CompressFormat.PNG, 100, out);
        bmp.recycle();

    } finally {
        if (out != null) {
            out.close();
        }
        if (in != null) {
            in.close();
        }
    }
}

From source file:com.perm.DoomPlay.PlayingService.java

private Notification createOldNotif() {
    NotificationCompat.Builder builder = new NotificationCompat.Builder(this);

    Intent intentActivity;//  ww w  .ja va  2 s .  c  o m

    if (SettingActivity.getPreferences(SettingActivity.keyOnClickNotif)) {
        intentActivity = new Intent(FullPlaybackActivity.actionReturnFull);
        intentActivity.setClass(this, FullPlaybackActivity.class);
        intentActivity.putExtra(FileSystemActivity.keyMusic, audios);
    } else {
        intentActivity = FullPlaybackActivity.getReturnSmallIntent(this, audios);
    }
    intentActivity.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    builder.setContentIntent(
            PendingIntent.getActivity(this, 0, intentActivity, PendingIntent.FLAG_UPDATE_CURRENT))
            .setOngoing(true)
            .setSmallIcon(isPlaying ? R.drawable.status_icon_pause : R.drawable.status_icon_play);

    Audio audio = audios.get(indexCurrentTrack);

    builder.setContentTitle(audio.getTitle());
    builder.setContentText(audio.getArtist());

    Bitmap cover = AlbumArtGetter.getBitmapFromStore(audio.getAid(), this);
    if (cover == null) {
        Bitmap tempBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.fallback_cover);
        builder.setLargeIcon(tempBitmap);
        tempBitmap.recycle();
    } else {
        builder.setLargeIcon(cover);
        cover.recycle();
    }

    return builder.build();
}

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  w  w  .  j a va 2 s.co 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) {
        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;
}