Android: Crop an Image after Taking it With Camera with a Fixed Aspect Ratio

I'm trying to crop an image after taking it, and my code is as follows:

   private void doTakePhotoAction() {

        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, MediaStore.Images.Media.EXTERNAL_CONTENT_URI.toString());
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 96);
        intent.putExtra("outputY", 96);

        try {
            intent.putExtra("return-data", true);
            startActivityForResult(intent, PICK_FROM_CAMERA);
        } catch (ActivityNotFoundException e) {
            //Do nothing for now
        }
    }

With the above code, I'm able to go to crop mode, and crop the picture. However, the 1:1 aspect ratio is not enforced, and neither is the outputX and outputY. I believe this is because the intent was for taking a picture, not for cropping. I've also written another method to getData() from the Intent, and after that use the following:

Intent intent = new Intent("com.android.camera.action.CROP");
intent.setClassName("com.android.camera", "com.android.camera.CropImage");

However, when I do that, I get the following runtime error:

E/AndroidRuntime(14648): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.android.camera/com.android.camera.CropImage}: java.lang.NullPointerException

Thanks for the help! :)


Asked by: Lily855 | Posted: 24-01-2022






Answer 1

After doing some reading, I realized it can't be done so simply. My modded Contacts source is at http://github.com/Wysie, you can take a look if you're interested. Also, here's what I did to get it working:

private void doTakePhotoAction() {
    // http://2009.hfoss.org/Tutorial:Camera_and_Gallery_Demo
    // http://stackoverflow.com/questions/1050297/how-to-get-the-url-of-the-captured-image
    // http://www.damonkohler.com/2009/02/android-recipes.html
    // http://www.firstclown.us/tag/android/
    // The one I used to get everything working: http://groups.google.com/group/android-developers/msg/2ab62c12ee99ba30 

    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

    //Wysie_Soh: Create path for temp file
    mImageCaptureUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(),
                        "tmp_contact_" + String.valueOf(System.currentTimeMillis()) + ".jpg"));

    intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, mImageCaptureUri);

    try {
        intent.putExtra("return-data", true);
        startActivityForResult(intent, PICK_FROM_CAMERA);
    } catch (ActivityNotFoundException e) {
        //Do nothing for now
    }
}

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode != RESULT_OK) {
        return;
    }

    switch (requestCode) {

    case CROP_FROM_CAMERA: {
        //Wysie_Soh: After a picture is taken, it will go to PICK_FROM_CAMERA, which will then come here
        //after the image is cropped.

        final Bundle extras = data.getExtras();

        if (extras != null) {
            Bitmap photo = extras.getParcelable("data");

            mPhoto = photo;
            mPhotoChanged = true;
            mPhotoImageView.setImageBitmap(photo);
            setPhotoPresent(true);
        }

        //Wysie_Soh: Delete the temporary file                        
        File f = new File(mImageCaptureUri.getPath());            
        if (f.exists()) {
            f.delete();
        }

        InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        mgr.showSoftInput(mPhotoImageView, InputMethodManager.SHOW_IMPLICIT);

        break;
    }

    case PICK_FROM_CAMERA: {
        //Wysie_Soh: After an image is taken and saved to the location of mImageCaptureUri, come here
        //and load the crop editor, with the necessary parameters (96x96, 1:1 ratio)

        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setClassName("com.android.camera", "com.android.camera.CropImage");

        intent.setData(mImageCaptureUri);
        intent.putExtra("outputX", 96);
        intent.putExtra("outputY", 96);
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("scale", true);
        intent.putExtra("return-data", true);            
        startActivityForResult(intent, CROP_FROM_CAMERA);

        break;

    }
    }
}

Hope it helps :)

Answered by: Daryl410 | Posted: 25-02-2022



Answer 2

Check out this post. I tested it on my android 1.5 (Htc Magic) and worked perfectly.

Android Works

Answered by: Kirsten379 | Posted: 25-02-2022



Answer 3

Have you tried this Intent (but keeping the crop/aspect/output/return-data extras you already have)?

Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");

That's basically what the Android contacts application does, so perhaps it won't quite fit your use case (i.e. taking a photo immediately, rather than having the option of selecting one from the gallery or taking a new photo).

Worth a try anyway! :)

Answered by: Emma334 | Posted: 25-02-2022



Answer 4

Though this might be a very old thread, I was able to crop a picture programmatically with the following code :

        btnTakePicture.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Intent cameraIntent = new Intent(
                    android.provider.MediaStore.ACTION_IMAGE_CAPTURE);

            startActivityForResult(cameraIntent, CAMERA_REQUEST);
        }
    });

then I cropped it with :

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {

        photo = (Bitmap) data.getExtras().get("data");

        performcrop();
    }

}

private void performcrop() {
    DisplayMetrics displayMetrics = this.getResources().getDisplayMetrics();
    int width = displayMetrics.widthPixels;
    int height = displayMetrics.heightPixels;

    Bitmap croppedBmp = Bitmap.createBitmap(photo, 0, 0, width / 2,
            photo.getHeight());

    imageTaken.setImageBitmap(croppedBmp);
}

imageTaken is an ImageView Component in my view. You can see my source Here

Answered by: Wilson312 | Posted: 25-02-2022



Similar questions

Android: view/ drawable custom styles possible?

What I'd like to do is change the state (really, the background) of an EditText to reflect validity of its contents. E.g. if the user enters 999 where 999 is contextually invalid, the EditText should have a red border in place of the default orange border, likewise once the text is valid it should have a green border. Methods I've explored: Changing the style of the EditText programmatically via some...


Android: Keep GPS active

i'm having a main activity that runs a gps listener. If i'm starting a new activity the listener is destroyed. I need the gps to be still activated, also after starting the 2nd activity. Do i have to implement an own listener there, or is there another solution?


Android: is it possible to add ZIP file as a raw resource and read it with ZipFile?

Is it possible to add ZIP file to APK package as a raw resource and read it with ZipFile class? It looks like it's trivial to open file from SD card, but not from APK.


adb - Android: Delete entire database

I would like to delete a complete database created by my application. Do you know any adb command, or android sentence to do it?


Android: Internal Linkify does not work properly, and text, images flicker inside ListView

I enabled the Linkify property of a textview as follows: txtbox.setAutoLinkMask(Linkify.WEB_URLS); But, when there are URLs like bit.ly are present (which is very common nowadays in messages like tweets), it doesn't display them properly. The problem is "sometimes" it succeeds and sometimes it fails... The other problem is, if this TextView is part of a custom view for a ListView, then unt...


menu - Android: Start activity from a MenuItem

I'm new on Android, and I'm trying to start an Activity from a MenuItem choose of the user. Actually, I'm building my menu (and is working OK) from my main activity class using a MenuInflater: @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); //the Menu Inflater class allows to create a menu from a XML File ...


Android: textView doesn't show cursor

I have a textView which is configured as an EditText. But the problem is that the cursor doesn't appear when i'm pressing keys (text is written correctly). Thanks


Android: Flush DNS

Closed. This question is off-topic. It is not curre...


Android: Handling Activity stack

I've got the following: Activities A, B, C, D. A and D can be reached at any time, anywhere from the application. B and C are reached like this: A -> B -> C I have the following use case: The user has entered C ( A -> B -> C ) then she has gone to D. ...


Android: Move whole layout upwards

I have a LinearLayout, when user selects my AutoCompleteTextView(ACTW) I want to move the whole layout upwards, so that the ACTW is at the top and there is space between the ACTW and software keyboard for suggestions. 1) How to do this? 2) How to make this animated (but this is not necessary)?






Still can't find your answer? Check out these communities...



Android Google Support | Android Community | Android Community (Facebook) | Dev.io Android



top