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.android.contacts.quickcontact.QuickContactActivity.java

/**
 * Asynchronously extract the most vibrant color from the PhotoView. Once extracted,
 * apply this tint to {@link MultiShrinkScroller}. This operation takes about 20-30ms
 * on a Nexus 5.//from  w ww.  j a  v a2s  .  co m
 */
private void extractAndApplyTintFromPhotoViewAsynchronously() {
    if (mScroller == null) {
        return;
    }
    final Drawable imageViewDrawable = mPhotoView.getDrawable();
    new AsyncTask<Void, Void, MaterialPalette>() {
        @Override
        protected MaterialPalette doInBackground(Void... params) {

            if (imageViewDrawable instanceof BitmapDrawable && mContactData != null
                    && mContactData.getThumbnailPhotoBinaryData() != null
                    && mContactData.getThumbnailPhotoBinaryData().length > 0) {
                // Perform the color analysis on the thumbnail instead of the full sized
                // image, so that our results will be as similar as possible to the Bugle
                // app.
                final Bitmap bitmap = BitmapFactory.decodeByteArray(mContactData.getThumbnailPhotoBinaryData(),
                        0, mContactData.getThumbnailPhotoBinaryData().length);
                try {
                    final int primaryColor = colorFromBitmap(bitmap);
                    if (primaryColor != 0) {
                        return mMaterialColorMapUtils.calculatePrimaryAndSecondaryColor(primaryColor);
                    }
                } finally {
                    bitmap.recycle();
                }
            }
            if (imageViewDrawable instanceof LetterTileDrawable) {
                final int primaryColor = ((LetterTileDrawable) imageViewDrawable).getColor();
                return mMaterialColorMapUtils.calculatePrimaryAndSecondaryColor(primaryColor);
            }
            return MaterialColorMapUtils.getDefaultPrimaryAndSecondaryColors(getResources());
        }

        @Override
        protected void onPostExecute(MaterialPalette palette) {
            super.onPostExecute(palette);
            if (mHasComputedThemeColor) {
                // If we had previously computed a theme color from the contact photo,
                // then do not update the theme color. Changing the theme color several
                // seconds after QC has started, as a result of an updated/upgraded photo,
                // is a jarring experience. On the other hand, changing the theme color after
                // a rotation or onNewIntent() is perfectly fine.
                return;
            }
            // Check that the Photo has not changed. If it has changed, the new tint
            // color needs to be extracted
            if (imageViewDrawable == mPhotoView.getDrawable()) {
                mHasComputedThemeColor = true;
                setThemeColor(palette);
                // update color and photo in suggestion card
                onAggregationSuggestionChange();
            }
        }
    }.execute();
}

From source file:com.fullteem.yueba.app.ui.ChatActivity.java

/**
 * onActivityResult//from  www . jav a2s  . co  m
 */
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_CODE_EXIT_GROUP) {
        setResult(RESULT_OK);
        finish();
        return;
    }
    if (requestCode == REQUEST_CODE_CONTEXT_MENU) {
        switch (resultCode) {
        case RESULT_CODE_COPY: // ??
            EMMessage copyMsg = (adapter.getItem(data.getIntExtra("position", -1)));
            // clipboard.setText(SmileUtils.getSmiledText(ChatActivity.this,
            // ((TextMessageBody) copyMsg.getBody()).getMessage()));
            clipboard.setText(((TextMessageBody) copyMsg.getBody()).getMessage());
            break;
        case RESULT_CODE_DELETE: // ?
            EMMessage deleteMsg = adapter.getItem(data.getIntExtra("position", -1));
            conversation.removeMessage(deleteMsg.getMsgId());
            adapter.refresh();
            listView.setSelection(data.getIntExtra("position", adapter.getCount()) - 1);
            break;

        case RESULT_CODE_FORWARD: // ??
            // EMMessage forwardMsg = (EMMessage)
            // adapter.getItem(data.getIntExtra("position", 0));
            // Intent intent = new Intent(this,
            // ForwardMessageActivity.class);
            // intent.putExtra("forward_msg_id", forwardMsg.getMsgId());
            // startActivity(intent);

            break;

        default:
            break;
        }
    }
    if (resultCode == RESULT_OK) { // ?
        if (requestCode == REQUEST_CODE_EMPTY_HISTORY) {
            // ?
            EMChatManager.getInstance().clearConversation(toChatUsername);
            adapter.refresh();
        } else if (requestCode == REQUEST_CODE_CAMERA) { // ??
            if (cameraFile != null && cameraFile.exists())
                sendPicture(cameraFile.getAbsolutePath());
        } else if (requestCode == REQUEST_CODE_SELECT_VIDEO) { // ??

            int duration = data.getIntExtra("dur", 0);
            String videoPath = data.getStringExtra("path");
            File file = new File(PathUtil.getInstance().getImagePath(), "thvideo" + System.currentTimeMillis());
            Bitmap bitmap = null;
            FileOutputStream fos = null;
            try {
                if (!file.getParentFile().exists()) {
                    file.getParentFile().mkdirs();
                }
                bitmap = ThumbnailUtils.createVideoThumbnail(videoPath, 3);
                if (bitmap == null) {
                    EMLog.d("chatactivity", "problem load video thumbnail bitmap,use default icon");
                    bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.app_panel_video_icon);
                }
                fos = new FileOutputStream(file);

                bitmap.compress(CompressFormat.JPEG, 100, fos);

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (fos != null) {
                    try {
                        fos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    fos = null;
                }
                if (bitmap != null) {
                    bitmap.recycle();
                    bitmap = null;
                }

            }
            sendVideo(videoPath, file.getAbsolutePath(), duration / 1000);

        } else if (requestCode == REQUEST_CODE_LOCAL) { // ??
            if (data != null) {
                Uri selectedImage = data.getData();
                if (selectedImage != null) {
                    sendPicByUri(selectedImage);
                }
            }
        } else if (requestCode == REQUEST_CODE_SELECT_FILE) { // ??
            if (data != null) {
                Uri uri = data.getData();
                if (uri != null) {
                    sendFile(uri);
                }
            }

        } else if (requestCode == REQUEST_CODE_MAP) { // 
            double latitude = data.getDoubleExtra("latitude", 0);
            double longitude = data.getDoubleExtra("longitude", 0);
            String locationAddress = data.getStringExtra("address");
            if (locationAddress != null && !locationAddress.equals("")) {
                more(more);
                sendLocationMsg(latitude, longitude, "", locationAddress);
            } else {
                Toast.makeText(this, "????", 0).show();
            }
            // ???
        } else if (requestCode == REQUEST_CODE_TEXT) {
            resendMessage();
        } else if (requestCode == REQUEST_CODE_VOICE) {
            resendMessage();
        } else if (requestCode == REQUEST_CODE_PICTURE) {
            resendMessage();
        } else if (requestCode == REQUEST_CODE_LOCATION) {
            resendMessage();
        } else if (requestCode == REQUEST_CODE_VIDEO || requestCode == REQUEST_CODE_FILE) {
            resendMessage();
        } else if (requestCode == REQUEST_CODE_COPY_AND_PASTE) {
            // 
            if (!TextUtils.isEmpty(clipboard.getText())) {
                String pasteText = clipboard.getText().toString();
                if (pasteText.startsWith(COPY_IMAGE)) {
                    // ??path
                    sendPicture(pasteText.replace(COPY_IMAGE, ""));
                }

            }
        } else if (requestCode == REQUEST_CODE_ADD_TO_BLACKLIST) { // ???
            EMMessage deleteMsg = adapter.getItem(data.getIntExtra("position", -1));
            addUserToBlacklist(deleteMsg.getFrom());
        } else if (conversation.getMsgCount() > 0) {
            adapter.refresh();
            setResult(RESULT_OK);
        } else if (requestCode == REQUEST_CODE_GROUP_DETAIL) {
            adapter.refresh();
        }
    }
}

From source file:com.kll.collect.android.activities.FormEntryActivity.java

private void compreesImage(String path) {

    Bitmap scaledBitmap = null;/*from w  ww . j av a  2s  .co m*/
    try {
        // Part 1: Decode image
        Bitmap unscaledBitmap = ScalingUtilities.decodeFile(path, ScalingUtilities.DESIREDWIDTH,
                ScalingUtilities.DESIREDHEIGHT, ScalingUtilities.ScalingLogic.FIT);

        if (!(unscaledBitmap.getWidth() <= 800 && unscaledBitmap.getHeight() <= 800)) {
            // Part 2: Scale image
            scaledBitmap = ScalingUtilities.createScaledBitmap(unscaledBitmap, ScalingUtilities.DESIREDWIDTH,
                    ScalingUtilities.DESIREDHEIGHT, ScalingUtilities.ScalingLogic.FIT);
        } else {
            unscaledBitmap.recycle();

        }

        // Store to tmp file

        File f = new File(path);

        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(f);
            scaledBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {

            e.printStackTrace();
        } catch (Exception e) {

            e.printStackTrace();
        }

        scaledBitmap.recycle();
    } catch (Throwable e) {
    }

}

From source file:com.logilite.vision.camera.CameraLauncher.java

/**
 * Applies all needed transformation to the image received from the gallery.
 *
 * @param destType          In which form should we return the image
 * @param intent            An Intent, which can return result data to the caller (various data can be attached to Intent "extras").
 *//*w  w  w.ja  v  a 2  s  .  co m*/
private void processResultFromGallery(int destType, Intent intent) {
    Uri uri = intent.getData();
    int rotate = 0;

    // If you ask for video or all media type you will automatically get back a file URI
    // and there will be no attempt to resize any returned data
    if (this.mediaType != PICTURE) {
        this.callbackContext.success(uri.toString());
    } else {
        // This is a special case to just return the path as no scaling,
        // rotating, nor compressing needs to be done
        if (this.targetHeight == -1 && this.targetWidth == -1
                && (destType == FILE_URI || destType == NATIVE_URI) && !this.correctOrientation) {
            this.callbackContext.success(uri.toString());
        } else {
            String uriString = uri.toString();
            // Get the path to the image. Makes loading so much easier.
            String mimeType = FileHelper.getMimeType(uriString, this.cordova);
            // If we don't have a valid image so quit.
            Bitmap bitmap = null;
            try {
                bitmap = getScaledBitmap(uriString);
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (bitmap == null) {
                Log.d(LOG_TAG, "I either have a null image path or bitmap");
                this.failPicture("Unable to create bitmap!");
                return;
            }

            if (this.correctOrientation) {
                rotate = getImageOrientation(uri);
                if (rotate != 0) {
                    Matrix matrix = new Matrix();
                    matrix.setRotate(rotate);
                    try {
                        bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(),
                                matrix, true);
                        this.orientationCorrected = true;
                    } catch (OutOfMemoryError oom) {
                        this.orientationCorrected = false;
                    }
                }
            }

            // If sending base64 image back
            if (destType == DATA_URL) {
                this.processPicture(bitmap);
            }

            // If sending filename back
            else if (destType == FILE_URI || destType == NATIVE_URI) {
                // Did we modify the image?
                if ((this.targetHeight > 0 && this.targetWidth > 0)
                        || (this.correctOrientation && this.orientationCorrected)) {
                    try {
                        String modifiedPath = this.ouputModifiedBitmap(bitmap, uri);
                        // The modified image is cached by the app in order to get around this and not have to delete you
                        // application cache I'm adding the current system time to the end of the file url.
                        this.callbackContext
                                .success("file://" + modifiedPath + "?" + System.currentTimeMillis());
                    } catch (Exception e) {
                        e.printStackTrace();
                        this.failPicture("Error retrieving image.");
                    }
                } else {
                    this.callbackContext.success(uri.toString());
                }
            }
            if (bitmap != null) {
                bitmap.recycle();
                bitmap = null;
            }
            System.gc();
        }
    }
}

From source file:com.cm.android.beercellar.ui.ImageGridFragment.java

private void insertSeedData() {
    new android.os.AsyncTask<Object, Void, Void>() {
        @Override//from   www . ja v a  2s  .c  om
        protected Void doInBackground(Object... params) {
            String seedDataSet = getActivity()
                    .getSharedPreferences(Utils.SHARED_PREF_NAME, Context.MODE_PRIVATE)
                    .getString("SEED_DATA_SET", "N");
            if (seedDataSet.equals("N")) {
                FileOutputStream out1 = null;
                FileOutputStream out2 = null;
                Bitmap bm1 = null;
                Bitmap bm2 = null;
                NotesDbAdapter dbHelper = null;
                long rowId = Math.abs(new Random(System.currentTimeMillis()).nextLong());

                try {
                    String imageAbsolutePath = Utils.getExternalImageStorageDir(getActivity())
                            .getAbsolutePath();
                    String thumbnailAbsolutePath = Utils.getExternalThumbnailStorageDir(getActivity())
                            .getAbsolutePath();

                    bm1 = BitmapFactory.decodeResource(getResources(), R.drawable.beer_label_icon);
                    File imageFile = new File(imageAbsolutePath, rowId + Utils.PICTURES_EXTENSION);
                    out1 = new FileOutputStream(imageFile);
                    bm1.compress(Bitmap.CompressFormat.PNG, 100, out1);

                    bm2 = BitmapFactory.decodeResource(getResources(), R.drawable.beer_label_icon);
                    File thumbnailFile = new File(thumbnailAbsolutePath, rowId + Utils.PICTURES_EXTENSION);
                    out2 = new FileOutputStream(thumbnailFile);
                    bm2.compress(Bitmap.CompressFormat.PNG, 100, out2);

                    Note note = new Note();
                    note.id = rowId;
                    note.beer = "Belgian Style Pale Ale";
                    note.rating = "4.0";
                    note.textExtract = "Chimay Blanche, Chimay Brewery, Chimay, Belgium";
                    note.notes = "Trappist beer";
                    //default to Y
                    note.share = "Y";
                    note.picture = rowId + Utils.PICTURES_EXTENSION;

                    dbHelper = new NotesDbAdapter(getActivity());
                    dbHelper.open();
                    dbHelper.createNote(note);

                    //finally
                    getActivity().getSharedPreferences(Utils.SHARED_PREF_NAME, Context.MODE_PRIVATE).edit()
                            .putString("SEED_DATA_SET", "Y").commit();
                } catch (Exception e) {
                    //do nothing
                } finally {
                    try {
                        out1.flush();
                        out1.close();
                        bm1.recycle();
                        out2.flush();
                        out2.close();
                        bm2.recycle();
                        if (dbHelper != null)
                            dbHelper.close();
                    } catch (Exception e) {//do nothing}
                    }
                }
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            mAdapter.notifyDataSetChanged();
        }
    }.execute();

}

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

/**
     * Applies all needed transformation to the image received from the gallery.
     */*from ww w .  j av a  2s .  c om*/
     * @param destType          In which form should we return the image
     * @param intent            An Intent, which can return result data to the caller (various data can be attached to Intent "extras").
     */
private void processResultFromGallery(int destType, Intent intent) {
    Uri uri = intent.getData();
    if (uri == null) {
        if (croppedUri != null) {
            uri = croppedUri;
        } else {
            this.failPicture("null data from photo library");
            return;
        }
    }
    int rotate = 0;

    // If you ask for video or all media type you will automatically get back a file URI
    // and there will be no attempt to resize any returned data
    if (this.mediaType != PICTURE) {
        this.callbackContext.success(uri.toString());
    } else {
        // This is a special case to just return the path as no scaling,
        // rotating, nor compressing needs to be done
        if (this.targetHeight == -1 && this.targetWidth == -1
                && (destType == FILE_URI || destType == NATIVE_URI) && !this.correctOrientation) {
            this.callbackContext.success(uri.toString());
        } else {
            String uriString = uri.toString();
            // Get the path to the image. Makes loading so much easier.
            String mimeType = FileHelper.getMimeType(uriString, this.activity);
            // If we don't have a valid image so quit.
            if (!("image/jpeg".equalsIgnoreCase(mimeType) || "image/png".equalsIgnoreCase(mimeType))) {
                Log.d(LOG_TAG, "I either have a null image path or bitmap");
                this.failPicture("Unable to retrieve path to picture!");
                return;
            }
            Bitmap bitmap = null;
            try {
                bitmap = getScaledBitmap(uriString);
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (bitmap == null) {
                Log.d(LOG_TAG, "I either have a null image path or bitmap");
                this.failPicture("Unable to create bitmap!");
                return;
            }

            if (this.correctOrientation) {
                rotate = getImageOrientation(uri);
                if (rotate != 0) {
                    Matrix matrix = new Matrix();
                    matrix.setRotate(rotate);
                    try {
                        bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(),
                                matrix, true);
                        this.orientationCorrected = true;
                    } catch (OutOfMemoryError oom) {
                        this.orientationCorrected = false;
                    }
                }
            }

            // If sending base64 image back
            if (destType == DATA_URL) {
                this.processPicture(bitmap);
            }

            // If sending filename back
            else if (destType == FILE_URI || destType == NATIVE_URI) {
                // Did we modify the image?
                if ((this.targetHeight > 0 && this.targetWidth > 0)
                        || (this.correctOrientation && this.orientationCorrected)) {
                    try {
                        String modifiedPath = this.ouputModifiedBitmap(bitmap, uri);
                        // The modified image is cached by the app in order to get around this and not have to delete you
                        // application cache I'm adding the current system time to the end of the file url.
                        this.callbackContext
                                .success("file://" + modifiedPath + "?" + System.currentTimeMillis());
                    } catch (Exception e) {
                        e.printStackTrace();
                        this.failPicture("Error retrieving image.");
                    }
                } else {
                    this.callbackContext.success(uri.toString());
                }
            }
            if (bitmap != null) {
                bitmap.recycle();
                bitmap = null;
            }
            System.gc();
        }
    }
}

From source file:com.remobile.camera.CameraLauncher.java

/**
 * Applies all needed transformation to the image received from the gallery.
 *
 * @param destType In which form should we return the image
 * @param intent   An Intent, which can return result data to the caller (various data can be attached to Intent "extras").
 *//*www .ja  v  a 2s . co  m*/
private void processResultFromGallery(int destType, Intent intent) {
    Uri uri = intent.getData();
    if (uri == null) {
        if (croppedUri != null) {
            uri = croppedUri;
        } else {
            this.failPicture("null data from photo library");
            return;
        }
    }
    int rotate = 0;

    // If you ask for video or all media type you will automatically get back a file URI
    // and there will be no attempt to resize any returned data
    if (this.mediaType != PICTURE) {
        this.callbackContext.success(uri.toString());
    } else {
        // This is a special case to just return the path as no scaling,
        // rotating, nor compressing needs to be done
        if (this.targetHeight == -1 && this.targetWidth == -1
                && (destType == FILE_URI || destType == NATIVE_URI) && !this.correctOrientation) {
            this.callbackContext.success(uri.toString());
        } else {
            String uriString = uri.toString();
            // Get the path to the image. Makes loading so much easier.
            String mimeType = FileHelper.getMimeType(uriString, this.cordova);
            // If we don't have a valid image so quit.
            if (!("image/jpeg".equalsIgnoreCase(mimeType) || "image/png".equalsIgnoreCase(mimeType))) {
                Log.d(LOG_TAG, "I either have a null image path or bitmap");
                this.failPicture("Unable to retrieve path to picture!");
                return;
            }
            Bitmap bitmap = null;
            try {
                bitmap = getScaledBitmap(uriString);
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (bitmap == null) {
                Log.d(LOG_TAG, "I either have a null image path or bitmap");
                this.failPicture("Unable to create bitmap!");
                return;
            }

            if (this.correctOrientation) {
                rotate = getImageOrientation(uri);
                if (rotate != 0) {
                    Matrix matrix = new Matrix();
                    matrix.setRotate(rotate);
                    try {
                        bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(),
                                matrix, true);
                        this.orientationCorrected = true;
                    } catch (OutOfMemoryError oom) {
                        this.orientationCorrected = false;
                    }
                }
            }

            // If sending base64 image back
            if (destType == DATA_URL) {
                this.processPicture(bitmap);
            }

            // If sending filename back
            else if (destType == FILE_URI || destType == NATIVE_URI) {
                // Did we modify the image?
                if ((this.targetHeight > 0 && this.targetWidth > 0)
                        || (this.correctOrientation && this.orientationCorrected)) {
                    try {
                        String modifiedPath = this.ouputModifiedBitmap(bitmap, uri);
                        // The modified image is cached by the app in order to get around this and not have to delete you
                        // application cache I'm adding the current system time to the end of the file url.
                        this.callbackContext
                                .success("file://" + modifiedPath + "?" + System.currentTimeMillis());
                    } catch (Exception e) {
                        e.printStackTrace();
                        this.failPicture("Error retrieving image.");
                    }
                } else {
                    this.callbackContext.success(uri.toString());
                }
            }
            if (bitmap != null) {
                bitmap.recycle();
                bitmap = null;
            }
            System.gc();
        }
    }
}

From source file:com.plugin.camera.ForegroundCameraLauncher.java

/**
 * Called when the camera view exits.//from  www  . j  a v  a  2 s.co m
 *
 * @param requestCode
 *            The request code originally supplied to
 *            startActivityForResult(), allowing you to identify who this
 *            result came from.
 * @param resultCode
 *            The integer result code returned by the child activity through
 *            its setResult().
 * @param intent
 *            An Intent, which can return result data to the caller (various
 *            data can be attached to Intent "extras").
 */
public void onActivityResult(int requestCode, int resultCode, Intent intent) {

    // If image available
    if (resultCode == Activity.RESULT_OK) {
        try {
            // Create an ExifHelper to save the exif data that is lost
            // during compression
            ExifHelper exif = new ExifHelper();
            exif.createInFile(
                    getTempDirectoryPath(this.cordova.getActivity().getApplicationContext()) + "/Pic.jpg");
            exif.readExifData();

            // Read in bitmap of captured image
            Bitmap bitmap;
            try {
                bitmap = android.provider.MediaStore.Images.Media
                        .getBitmap(this.cordova.getActivity().getContentResolver(), imageUri);
            } catch (FileNotFoundException e) {
                Uri uri = intent.getData();
                android.content.ContentResolver resolver = this.cordova.getActivity().getContentResolver();
                bitmap = android.graphics.BitmapFactory.decodeStream(resolver.openInputStream(uri));
            }

            bitmap = scaleBitmap(bitmap);

            // Create entry in media store for image
            // (Don't use insertImage() because it uses default compression
            // setting of 50 - no way to change it)
            ContentValues values = new ContentValues();
            values.put(android.provider.MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
            Uri uri = null;
            try {
                uri = this.cordova.getActivity().getContentResolver()
                        .insert(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
            } catch (UnsupportedOperationException e) {
                LOG.d(LOG_TAG, "Can't write to external media storage.");
                try {
                    uri = this.cordova.getActivity().getContentResolver()
                            .insert(android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI, values);
                } catch (UnsupportedOperationException ex) {
                    LOG.d(LOG_TAG, "Can't write to internal media storage.");
                    this.failPicture("Error capturing image - no media storage found.");
                    return;
                }
            }
            //This if block is added to the plugin to solve the issue which was saving portrait images in landscape with -90 degree rotetion
            if (intent.getBooleanExtra("portrait", false)) {
                Matrix matrix = new Matrix();
                matrix.preRotate(90);
                try {
                    bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix,
                            true);
                } catch (Exception e) {
                    bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth() / 2, bitmap.getHeight() / 2,
                            matrix, true);
                    e.printStackTrace();
                }
            }

            // Add compressed version of captured image to returned media
            // store Uri
            OutputStream os = this.cordova.getActivity().getContentResolver().openOutputStream(uri);
            bitmap.compress(Bitmap.CompressFormat.JPEG, this.mQuality, os);
            os.close();

            // Restore exif data to file
            exif.createOutFile(getRealPathFromURI(uri, this.cordova));
            exif.writeExifData();

            // Send Uri back to JavaScript for viewing image
            this.callbackContext.success(getRealPathFromURI(uri, this.cordova));

            bitmap.recycle();
            bitmap = null;
            System.gc();

            checkForDuplicateImage();
        } catch (IOException e) {
            e.printStackTrace();
            this.failPicture("Error capturing image.");
        }
    }

    // If cancelled
    else if (resultCode == Activity.RESULT_CANCELED) {
        this.failPicture("Camera cancelled.");
    }

    // If something else
    else {
        this.failPicture("Did not complete!");
    }
}

From source file:org.cryptsecure.Utility.java

/**
 * Get a resized version of a bitmap image.
 * // www.j a v  a2 s .  c o m
 * @param bitmap
 *            the bitmap
 * @param maxWidth
 *            the max width
 * @param maxHeight
 *            the max height
 * @return the resized image
 */
public static Bitmap getResizedImage(Bitmap bitmap, int maxWidth, int maxHeight, boolean deleteSource,
        boolean clipped) {
    int bitmapWidth = bitmap.getWidth();
    int bitmapHeight = bitmap.getHeight();
    int newWidth = bitmapWidth;
    int newHeight = bitmapHeight;

    Log.d("communicator", "RESIZE: maxWidth=" + maxWidth + ", maxHeight=" + maxHeight);
    Log.d("communicator", "RESIZE: bmpW=" + bitmapWidth + ", bmpH=" + bitmapHeight);

    boolean landscape = bitmapWidth > bitmapHeight;
    if (clipped) {
        landscape = !landscape;
    }

    if (landscape) {
        // Log.d("communicator", "RESIZE Landscape: bitmapWidth="
        // + bitmapWidth + " >? " + maxWidth + "=maxWidth");
        // Landscape
        // if (bitmapWidth > maxWidth) {
        float scale = ((float) bitmapWidth) / ((float) maxWidth);
        // Log.d("communicator", "RESIZE: (1) scale=" + scale);
        newWidth = maxWidth;
        newHeight = (int) ((float) bitmapHeight / scale);
        // } else if (bitmapHeight > maxHeight) {
        // float scale = ((float) bitmapHeight) / ((float) maxHeight);
        // // Log.d("communicator", "RESIZE: (2) scale=" + scale);
        // newHeight = maxHeight;
        // newWidth = (int) ((float) bitmapWidth / scale);
        // }

    } else {
        // Log.d("communicator", "RESIZE Portrait: bitmapHeight="
        // + bitmapHeight + " >? " + maxHeight + "=maxHeight");
        // Portrait
        // if (bitmapHeight > maxHeight) {
        float scale = ((float) bitmapHeight) / ((float) maxHeight);
        // Log.d("communicator", "RESIZE: (3) scale=" + scale);
        newHeight = maxHeight;
        newWidth = (int) ((float) bitmapWidth / scale);
        // } else if (bitmapWidth > maxWidth) {
        // float scale = ((float) bitmapWidth) / ((float) maxWidth);
        // // Log.d("communicator", "RESIZE: (4) scale=" + scale);
        // newWidth = maxWidth;
        // newHeight = (int) ((float) bitmapHeight / scale);
        // }
    }
    Log.d("communicator", "RESIZE RESULT: newWidth=" + newWidth + ", " + newHeight + "=newHeight");
    Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmap, newWidth, newHeight, true);

    if (deleteSource) {
        bitmap.recycle();
        System.gc();
    }

    if (clipped) {
        Bitmap clippedBitmap = Bitmap.createBitmap(scaledBitmap, ((newWidth - maxWidth) / 2),
                ((newHeight - maxHeight) / 2), maxWidth, maxHeight);

        Log.d("communicator",
                "RESIZE RESULT2: width=" + clippedBitmap.getWidth() + ", height=" + clippedBitmap.getHeight());

        scaledBitmap.recycle();
        System.gc();
        return clippedBitmap;
    }

    return scaledBitmap;
}

From source file:com.tealeaf.TeaLeaf.java

protected void onActivityResult(int request, int result, Intent data) {
    super.onActivityResult(request, result, data);
    PluginManager.callAll("onActivityResult", request, result, data);
    logger.log("GOT ACTIVITY RESULT WITH", request, result);

    switch (request) {
    case PhotoPicker.CAPTURE_IMAGE:
        if (result == RESULT_OK) {
            EventQueue.pushEvent(new PhotoBeginLoadedEvent());
            Bitmap bmp = null;

            if (data != null) {
                Bundle extras = data.getExtras();
                //try and get bitmap off of intent
                if (extras != null) {
                    bmp = (Bitmap) extras.get("data");
                }/* ww w  . j a va  2  s.  co m*/

            }

            //try the large file on disk
            final File f = PhotoPicker.getCaptureImageTmpFile();
            if (f != null && f.exists()) {
                new Thread(new Runnable() {
                    public void run() {
                        Bitmap bmp = null;
                        String filePath = f.getAbsolutePath();

                        try {
                            bmp = BitmapFactory.decodeFile(filePath);
                        } catch (OutOfMemoryError e) {
                            System.gc();
                            BitmapFactory.Options options = new BitmapFactory.Options();
                            options.inSampleSize = 4;
                            bmp = BitmapFactory.decodeFile(filePath, options);
                        }

                        if (bmp != null) {
                            try {
                                File f = new File(filePath);
                                ExifInterface exif = new ExifInterface(f.getAbsolutePath());
                                int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION,
                                        ExifInterface.ORIENTATION_NORMAL);
                                if (orientation != ExifInterface.ORIENTATION_NORMAL) {
                                    int rotateBy = 0;
                                    switch (orientation) {
                                    case ExifInterface.ORIENTATION_ROTATE_90:
                                        rotateBy = ROTATE_90;
                                        break;
                                    case ExifInterface.ORIENTATION_ROTATE_180:
                                        rotateBy = ROTATE_180;
                                        break;
                                    case ExifInterface.ORIENTATION_ROTATE_270:
                                        rotateBy = ROTATE_270;
                                        break;
                                    }
                                    Bitmap rotatedBmp = rotateBitmap(bmp, rotateBy);
                                    if (rotatedBmp != bmp) {
                                        bmp.recycle();
                                    }
                                    bmp = rotatedBmp;
                                }
                            } catch (Exception e) {
                                logger.log(e);
                            }
                            f.delete();

                            if (bmp != null) {
                                glView.getTextureLoader()
                                        .saveCameraPhoto(glView.getTextureLoader().getCurrentPhotoId(), bmp);
                                glView.getTextureLoader().finishCameraPicture();
                            } else {
                                glView.getTextureLoader().failedCameraPicture();
                            }
                        }
                    }
                }).start();

            } else {
                glView.getTextureLoader().saveCameraPhoto(glView.getTextureLoader().getCurrentPhotoId(), bmp);
                glView.getTextureLoader().finishCameraPicture();
            }
        } else {
            glView.getTextureLoader().failedCameraPicture();
        }
        break;
    case PhotoPicker.PICK_IMAGE:
        if (result == RESULT_OK) {
            final Uri selectedImage = data.getData();
            EventQueue.pushEvent(new PhotoBeginLoadedEvent());

            String[] filePathColumn = { MediaColumns.DATA, MediaStore.Images.ImageColumns.ORIENTATION };

            String _filepath = null;

            try {
                Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
                cursor.moveToFirst();

                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                _filepath = cursor.getString(columnIndex);
                columnIndex = cursor.getColumnIndex(filePathColumn[1]);
                int orientation = cursor.getInt(columnIndex);
                cursor.close();
            } catch (Exception e) {

            }

            final String filePath = _filepath;

            new Thread(new Runnable() {
                public void run() {
                    if (filePath == null) {
                        BitmapFactory.Options options = new BitmapFactory.Options();
                        InputStream inputStream;
                        Bitmap bmp = null;

                        try {
                            inputStream = getContentResolver().openInputStream(selectedImage);
                            bmp = BitmapFactory.decodeStream(inputStream, null, options);
                            inputStream.close();
                        } catch (Exception e) {
                            logger.log(e);

                        }

                        if (bmp != null) {
                            glView.getTextureLoader()
                                    .saveGalleryPicture(glView.getTextureLoader().getCurrentPhotoId(), bmp);
                            glView.getTextureLoader().finishGalleryPicture();
                        } else {
                            glView.getTextureLoader().failedGalleryPicture();
                        }

                    } else {
                        Bitmap bmp = null;

                        try {
                            bmp = BitmapFactory.decodeFile(filePath);
                        } catch (OutOfMemoryError e) {
                            System.gc();
                            BitmapFactory.Options options = new BitmapFactory.Options();
                            options.inSampleSize = 4;
                            bmp = BitmapFactory.decodeFile(filePath, options);
                        }

                        if (bmp != null) {
                            try {
                                File f = new File(filePath);
                                ExifInterface exif = new ExifInterface(f.getAbsolutePath());
                                int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION,
                                        ExifInterface.ORIENTATION_NORMAL);
                                if (orientation != ExifInterface.ORIENTATION_NORMAL) {
                                    int rotateBy = 0;
                                    switch (orientation) {
                                    case ExifInterface.ORIENTATION_ROTATE_90:
                                        rotateBy = ROTATE_90;
                                        break;
                                    case ExifInterface.ORIENTATION_ROTATE_180:
                                        rotateBy = ROTATE_180;
                                        break;
                                    case ExifInterface.ORIENTATION_ROTATE_270:
                                        rotateBy = ROTATE_270;
                                        break;
                                    }
                                    Bitmap rotatedBmp = rotateBitmap(bmp, rotateBy);
                                    if (rotatedBmp != bmp) {
                                        bmp.recycle();
                                    }
                                    bmp = rotatedBmp;
                                }
                            } catch (Exception e) {
                                logger.log(e);
                            }

                            if (bmp != null) {
                                glView.getTextureLoader()
                                        .saveGalleryPicture(glView.getTextureLoader().getCurrentPhotoId(), bmp);
                                glView.getTextureLoader().finishGalleryPicture();
                            } else {
                                glView.getTextureLoader().failedGalleryPicture();
                            }
                        }
                    }
                }
            }).start();

        } else {
            glView.getTextureLoader().failedGalleryPicture();
        }
        break;
    }
}