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:ch.ethz.dcg.jukefox.manager.libraryimport.AndroidAlbumCoverFetcherThread.java

private void saveImage(Bitmap bitmap, String fileName) throws CouldNotSaveCoverException {
    try {/*from   w w w. j  a v a 2 s . c o  m*/
        FileOutputStream stream = new FileOutputStream(fileName);
        bitmap.compress(Bitmap.CompressFormat.JPEG, 85, stream);
        bitmap.recycle();
        stream.close();
    } catch (Exception e) {
        Log.w(TAG, e);
        throw new CouldNotSaveCoverException(e.getMessage(), e);
    }
}

From source file:com.futurologeek.smartcrossing.crop.CropImageActivity.java

private void saveOutput(Bitmap croppedImage) throws IOException {
    saveUri = saveFileFromBitmap(croppedImage);
    filePath = getPath(CropImageActivity.this, saveUri);

    final Bitmap b = croppedImage;
    handler.post(new Runnable() {
        public void run() {
            imageView.clear();/*w ww .j a  v  a  2  s  .  c  o m*/
            b.recycle();
        }
    });

    Thread thread = new Thread(new Runnable() {

        @Override
        public void run() {
            try {
                POSTHandler han = new POSTHandler();
                JSONObject par = new JSONObject();
                try {
                    par.put("user_auth_token", UserInfo.token);
                    par.put("book_title", title);
                    par.put("book_author", author);
                    par.put("book_isbn", ISBN);
                    par.put("book_publication_date", book_year);
                    par.put("book_category", GetCategory.returnCatCode(CropImageActivity.this, cat));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                ob = han.handlePOSTmethodAddBook(filePath, par);
                CropImageActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (ob.has("error")) {
                            if (ob.has("sub_error")) {
                                int sub_error = 0;
                                try {
                                    sub_error = ob.getInt("sub_error");
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                                sub_error = sub_error * -1;
                                try {
                                    Toast.makeText(CropImageActivity.this,
                                            getResources().getString(R.string.JUST_ERROR) + " "
                                                    + GetStringCode.getErrorResource(ob.getInt("error"),
                                                            CropImageActivity.this)
                                                    + getResources().getString(R.string.ADDITIONAL_ERROR_INFO)
                                                    + " " + GetStringCode.getErrorResource(sub_error,
                                                            CropImageActivity.this),
                                            Toast.LENGTH_SHORT).show();
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            } else {
                                try {
                                    Toast.makeText(CropImageActivity.this,
                                            getResources().getString(R.string.JUST_ERROR) + " "
                                                    + GetStringCode.getErrorResource(ob.getInt("error"),
                                                            CropImageActivity.this),
                                            Toast.LENGTH_SHORT).show();
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                            finish();
                        } else {
                            try {
                                Toast.makeText(
                                        CropImageActivity.this, GetStringCode
                                                .getSuccessCode(ob.getInt("success"), CropImageActivity.this),
                                        Toast.LENGTH_SHORT).show();
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            finish();
                        }
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });

    thread.start();

}

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}.
 *///from  www.ja  v  a2  s . c om
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) {
        if (imagePath != null) {
            Log.w("Helper", "Cannot decode " + imagePath);
        } else {
            Log.w("Helper", "Path is null: Cannot decode");
        }
        return null;
    }

    if (image.getWidth() != width || image.getHeight() != height) {
        //Image need to be resized.
        int scaledWidth = (image.getWidth() * height) / image.getHeight();
        int scaledHeight;
        if ((crop && scaledWidth > width) || (!crop && scaledWidth < width)) {
            scaledHeight = height;
        } else {
            scaledWidth = width;
            scaledHeight = (image.getHeight() * width) / image.getWidth();
        }

        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.ibuildapp.romanblack.FanWallPlugin.data.Statics.java

/**
 * Sets the downloaded avatar./*  w w  w .  j a v a  2 s  .  co  m*/
 *
 * @param filePath file path to avatar image
 */
public static Bitmap publishAvatar(String filePath) {
    Bitmap bitmap = null;

    if (!TextUtils.isEmpty(filePath)) {
        try {
            BitmapFactory.Options opts = new BitmapFactory.Options();
            opts.inSampleSize = 1;
            bitmap = BitmapFactory.decodeFile(filePath, opts);
            int size = 0;
            if (bitmap.getHeight() > bitmap.getWidth()) {
                size = bitmap.getWidth();
            } else {
                size = bitmap.getHeight();
            }
            Bitmap output = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
            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 = 12;

            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) {

        }
    }
    return null;
}

From source file:com.fvd.nimbus.MainActivity.java

@SuppressLint("NewApi")
@Override/*from w w w  .  j  a va 2 s .com*/
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == TAKE_PHOTO) {
        if (resultCode == -1) {
            try {
                if (data != null) {
                    if (data.hasExtra("data")) {
                        Bitmap bm = data.getParcelableExtra("data");
                        photoFileName = appSettings.saveTempBitmap(bm);
                        bm.recycle();
                    }
                } else {
                    if (outputFileUri != null)
                        photoFileName = outputFileUri.getPath();
                    else
                        photoFileName = getImagePath();
                }

                if (appSettings.isFileExists(photoFileName)) {
                    Intent iPaint = new Intent();
                    iPaint.putExtra("temp", true);
                    iPaint.putExtra("path", photoFileName);
                    iPaint.setClassName("com.fvd.nimbus", "com.fvd.nimbus.PaintActivity");
                    startActivity(iPaint);
                }
                showProgress(false);
            } catch (Exception e) {
                appSettings.appendLog("main:onActivityResult: exception -  " + e.getMessage());
                showProgress(false);
            }
        } else
            showProgress(false);
    } else if (requestCode == TAKE_PICTURE) {
        if (resultCode == -1 && data != null) {
            boolean temp = false;

            try {
                Uri resultUri = data.getData();
                String drawString = resultUri.getPath();
                String galleryString = getGalleryPath(resultUri);
                if (galleryString != null && galleryString.length() > 0) {
                    drawString = galleryString;
                } else {
                    try {
                        InputStream input = getApplicationContext().getContentResolver()
                                .openInputStream(resultUri);
                        Bitmap bm = BitmapFactory.decodeStream(input);
                        drawString = appSettings.saveTempBitmap(bm);
                        bm.recycle();
                        temp = true;

                    } catch (Exception e) {
                        drawString = "";
                        showProgress(false);
                    }
                }

                if (drawString.length() > 0 && drawString.indexOf("/exposed_content/") == -1) {
                    try {
                        Intent iPaint = new Intent();
                        iPaint.putExtra("temp", temp);
                        iPaint.putExtra("path", drawString);
                        iPaint.setClassName("com.fvd.nimbus", "com.fvd.nimbus.PaintActivity");
                        startActivity(iPaint);
                    } catch (Exception e) {

                    }
                }
                showProgress(false);

            } catch (Exception e) {
                appSettings.appendLog("main:onActivityResult  " + e.getMessage());
                showProgress(false);
            }
        } else
            showProgress(false);
    } else if (requestCode == 5) {
        if (resultCode == RESULT_OK) {
            userMail = data.getStringExtra("userMail");
            userPass = data.getStringExtra("userPass");
            serverHelper.getInstance().sendOldRequest("user_register", String.format(
                    "{\"action\": \"user_register\",\"email\":\"%s\",\"password\":\"%s\",\"_client_software\": \"ff_addon\"}",
                    userMail, userPass), "");
        }
    } else if (requestCode == 6) {
        showLogin();
    } else if (requestCode == SHOW_SETTINGS) {
        switch (resultCode) {
        case RESULT_FIRST_USER + 1:
            Intent i = new Intent(getApplicationContext(), PrefsActivity.class);
            startActivity(i);
            //overridePendingTransition( R.anim.slide_in_up, R.anim.slide_out_up );
            overridePendingTransition(R.anim.carbon_slide_in, R.anim.carbon_slide_out);
            break;
        case RESULT_FIRST_USER + 2:
            if (appSettings.sessionId.length() == 0)
                showLogin();
            else {
                if (true || appSettings.service == "") {
                    appSettings.sessionId = "";
                    Editor e = prefs.edit();
                    e.putString("userMail", userMail);
                    e.putString("userPass", "");
                    e.putString("sessionId", appSettings.sessionId);
                    e.commit();
                    showLogin();
                } else {
                    i = new Intent(getApplicationContext(), loginWithActivity.class);
                    i.putExtra("logout", "true");
                    i.putExtra("service", appSettings.service);
                    startActivity(i);
                    overridePendingTransition(R.anim.carbon_slide_in, R.anim.carbon_slide_out);
                }
            }
            break;
        case RESULT_FIRST_USER + 3:
            try {
                startActivity(new Intent(Intent.ACTION_VIEW,
                        Uri.parse("market://details?id=" + getApplicationInfo().packageName)));
            } catch (Exception e) {
            }
        case RESULT_FIRST_USER + 4:
            Uri uri = Uri.parse(
                    "http://help.everhelper.me/customer/portal/articles/1376820-nimbus-clipper-for-android---quick-guide");
            Intent it = new Intent(Intent.ACTION_VIEW, uri);
            startActivity(it);
            //overridePendingTransition( R.anim.slide_in_up, R.anim.slide_out_up );
            overridePendingTransition(R.anim.carbon_slide_in, R.anim.carbon_slide_out);
            break;
        case RESULT_FIRST_USER + 5:
            final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this,
                    AlertDialog.THEME_DEVICE_DEFAULT_LIGHT);
            alertDialogBuilder.setMessage(getScriptContent("license.txt")).setCancelable(false)
                    .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            // no alert dialog shown
                            //alertDialogShown = null;
                            // canceled
                            setResult(RESULT_CANCELED);
                            // and finish
                            //finish();
                        }
                    });
            // create alert dialog
            final AlertDialog alertDialog = alertDialogBuilder.create();
            alertDialog.setTitle(getString(R.string.license_title));

            // and show
            //alertDialogShown = alertDialog;
            try {
                alertDialog.show();
            } catch (final java.lang.Exception e) {
                // nothing to do
            } catch (final java.lang.Error e) {
                // nothing to do
            }
            break;
        default:
            break;
        }
    }
}

From source file:com.netcompss.ffmpeg4android_client.BaseVideo.java

@SuppressWarnings("unused")
private String reporteds(String path) {

    ExifInterface exif = null;//from w w w.jav a2  s  . c o  m
    try {
        exif = new ExifInterface(path);
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
    Matrix matrix = new Matrix();
    if (orientation == 6) {
        matrix.postRotate(90);
    } else if (orientation == 3) {
        matrix.postRotate(180);
    } else if (orientation == 8) {
        matrix.postRotate(270);
    }

    if (path != null) {

        if (path.contains("http")) {
            try {
                URL url = new URL(path);
                HttpGet httpRequest = null;

                httpRequest = new HttpGet(url.toURI());

                HttpClient httpclient = new DefaultHttpClient();
                HttpResponse response = (HttpResponse) httpclient.execute(httpRequest);

                HttpEntity entity = response.getEntity();
                BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity);
                InputStream input = bufHttpEntity.getContent();

                Bitmap bitmap = BitmapFactory.decodeStream(input);
                input.close();
                return getPath(bitmap);
            } catch (MalformedURLException e) {
                Log.e("ImageActivity", "bad url", e);
            } catch (Exception e) {
                Log.e("ImageActivity", "io error", e);
            }
        } else {

            Options options = new Options();
            options.inSampleSize = 2;
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeResource(context.getResources(), srcBgId, options);
            options.inJustDecodeBounds = false;
            options.inSampleSize = calculateInSampleSize(options, w, h);
            Bitmap unbgbtmp = BitmapFactory.decodeResource(context.getResources(), srcBgId, options);
            Bitmap unrlbtmp = ScalingUtilities.decodeFile(path, w, h, ScalingLogic.FIT);
            unrlbtmp.recycle();
            Bitmap rlbtmp = null;
            if (unrlbtmp != null) {
                rlbtmp = ScalingUtilities.createScaledBitmap(unrlbtmp, w, h, ScalingLogic.FIT);
            }
            if (unbgbtmp != null && rlbtmp != null) {
                Bitmap bgbtmp = ScalingUtilities.createScaledBitmap(unbgbtmp, w, h, ScalingLogic.FIT);
                Bitmap newscaledBitmap = ProcessingBitmapTwo(bgbtmp, rlbtmp);
                unbgbtmp.recycle();
                return getPath(newscaledBitmap);
            }
        }
    }
    return path;

}

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

private void loadMusic() {
    dispose();//from ww  w .j  a  va 2  s.  co  m

    //TODO: sometimes it throws  java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0 , it's need to be fixed
    if (audios == null || audios.size() == 0)
        return;
    updateWidgets();
    sendBroadcast(new Intent(actionTrackChanged));
    if (isPlaying)
        sendBroadcast(new Intent(actionIconPause));
    else
        sendBroadcast(new Intent(actionIconPlay));

    startNotif();
    setBroadcast();

    new AsyncTask<Void, String, Void>() {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            isLoadingTrack = true;

            if (loadingListener != null)
                loadingListener.onLoadingTrackStarted();
        }

        @Override
        protected Void doInBackground(Void... params) {
            try {
                if (isOnline)
                    bassPlayer.prepareNet(audios.get(indexCurrentTrack).getUrl());

                else
                    bassPlayer.prepareFile(audios.get(indexCurrentTrack).getUrl());
            } catch (IOException e) {
                cancel(false);
                e.printStackTrace();
            }

            return null;
        }

        @Override
        protected void onCancelled() {
            super.onCancelled();

            isLoadingTrack = false;
            if (loadingListener != null)
                loadingListener.onLoadingTrackEnded();

            Toast.makeText(getBaseContext(), getResources().getString(R.string.error), Toast.LENGTH_SHORT)
                    .show();
            isPlaying = false;

            sendBroadcast(new Intent(actionIconPlay));
            sendBroadcast(new Intent(SmallWidget.actionUpdateWidget));
            startNotif();
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            isPrepared = true;

            isLoadingTrack = false;
            if (loadingListener != null)
                loadingListener.onLoadingTrackEnded();

            if (isPlaying) {
                bassPlayer.start();
            }

            Bitmap tempBitmap = AlbumArtGetter.getBitmapFromStore(audios.get(indexCurrentTrack).getAid(),
                    getBaseContext());

            if (tempBitmap == null)
                downloadAlbumArt(audios.get(indexCurrentTrack));
            else
                tempBitmap.recycle();
        }
    }.execute();

}

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

/** Decodes image file into Bitmap, resize it and save it back */
private boolean resizeAndSaveImage(int maxWidth, int maxHeight) throws IOException, JSONException {
    // Decode image file, compress and re-save it
    boolean saved = false;
    File targetFile = configuration.diskCache.get(uri);
    if (targetFile != null && targetFile.exists()) {
        ImageSize targetImageSize = new ImageSize(maxWidth, maxHeight);
        DisplayImageOptions specialOptions = new DisplayImageOptions.Builder().cloneFrom(options)
                .imageScaleType(ImageScaleType.IN_SAMPLE_INT).build();
        ImageDecodingInfo decodingInfo = new ImageDecodingInfo(memoryCacheKey,
                Scheme.FILE.wrap(targetFile.getAbsolutePath()), uri, targetImageSize, ViewScaleType.FIT_INSIDE,
                getDownloader(), specialOptions);
        Bitmap bmp = decoder.decode(decodingInfo);
        if (bmp != null && configuration.processorForDiskCache != null) {
            L.d(LOG_PROCESS_IMAGE_BEFORE_CACHE_ON_DISK, memoryCacheKey);
            bmp = configuration.processorForDiskCache.process(bmp);
            if (bmp == null) {
                L.e(ERROR_PROCESSOR_FOR_DISK_CACHE_NULL, memoryCacheKey);
            }/*from   w ww.  j  a v a 2 s.c o m*/
        }
        if (bmp != null) {
            saved = configuration.diskCache.save(uri, bmp);
            bmp.recycle();
        }
    }
    return saved;
}

From source file:cn.jmessage.android.uikit.pickerimage.view.BaseZoomableImageView.java

/**
 * //from w  ww  .  java  2s.  c om
 * Sets the bitmap for the image and resets the base
 * @date 2014-4-29
 * @param bitmap
 * @param selection
 */
public void setImageBitmap(final Bitmap bitmap, final Rect selection) {
    final int viewWidth = getWidth();

    if (viewWidth <= 0) {
        mOnLayoutRunnable = new Runnable() {
            public void run() {
                setImageBitmap(bitmap, updateSelection());
            }
        };
        return;
    }

    Bitmap oldBitmap = this.mBitmap;
    if (bitmap != null) {
        setBaseMatrix(bitmap, mBaseMatrix, selection);
        this.mBitmap = bitmap;
    } else {
        mBaseMatrix.reset();
        this.mBitmap = bitmap;
    }
    if (oldBitmap != null && !oldBitmap.isRecycled()) {
        oldBitmap.recycle();
    }

    mSuppMatrix.reset();
    setImageMatrix(getImageViewMatrix());
    mMaxZoom = maxZoom();

}

From source file:com.cordova.photo.CameraLauncher.java

/**
 * Cleans up after picture taking. Checking for duplicates and that kind of stuff.
 * @param newImage/*from   w  w w  .j  a  v a2 s .  co  m*/
 */
private void cleanup(int imageType, Uri oldImage, Uri newImage, Bitmap bitmap) {
    if (bitmap != null) {
        bitmap.recycle();
    }

    // Clean up initial camera-written image file.
    (new File(FileHelper.stripFileProtocol(oldImage.toString()))).delete();

    checkForDuplicateImage(imageType);
    // Scan for the gallery to update pic refs in gallery
    if (this.saveToPhotoAlbum && newImage != null) {
        this.scanForGallery(newImage);
    }

    System.gc();
}