logo logo

How to Select and Crop Image on Android

Home » Information Technology » Programming » Android » How to Select and Crop Image on Android




Sometimes when creating an Android app that includes user profile picture or avatar, we need to include a feature that enables users to select and crop image to update their profile picture. On Android we can accomplish that by using intent to open image cropper app. To select an image from files, we can pass an intent to image gallery or file manager app then pass the selected image path to camera app to crop the image. It is also the same if we want to take a picture from camera, by passing an intent to camera app to open the camera, take a picture than save it to specified Uri then crop it.

I’ve created a sample project to show how to select and crop image from files or from camera. The source files can be downloaded from my github repository (see the bottom if this post).

MainActivity.java

 final String [] items	      = new String [] {"Take from camera", "Select from Gallery"};
 ArrayAdapter<String> adapter = new ArrayAdapter<String> (this, android.R.layout.select_dialog_item,items);
 AlertDialog.Builder builder  = new AlertDialog.Builder(this);

 builder.setTitle("Select Image");
 builder.setAdapter( adapter, new DialogInterface.OnClickListener() {
    public void onClick( DialogInterface dialog, int item ) { //pick from camer
	if (item == 0) {
	    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

	    mImageCaptureUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(),
				 "tmp_avatar_" + 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) {
		e.printStackTrace();
	    }
       } else { //pick from file
	   Intent intent = new Intent();

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

	   startActivityForResult(Intent.createChooser(intent, "Complete action using"), PICK_FROM_FILE);
       }
    }
 } );

final AlertDialog dialog = builder.create();

Button button 	= (Button) findViewById(R.id.btn_crop);
mImageView	= (ImageView) findViewById(R.id.iv_photo);

button.setOnClickListener(new View.OnClickListener() {
   @Override
   public void onClick(View v) {
	dialog.show();
   }
});

Line 1: In this example, i use a selector dialog to display two image source options, from camera ‘Take from camera’ and from existing files ‘Select from gallery’

Line 9: To take a photo from camera, pass intent action ‘MediaStore.ACTION_IMAGE_CAPTURE‘ to open the camera app.
Line 11: Also specify the Uri to save the image on specified path and file name. Note that this Uri variable also used by gallery app to hold the selected image path.
Line 24-29: To select an image from existing files, use Intent.createChooser to open image chooser. Android will automatically display a list of supported applications, such as image gallery or file manager.

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
   if (resultCode != RESULT_OK) return;
       switch (requestCode) {
          case PICK_FROM_CAMERA:
	     doCrop();
             break;

          case PICK_FROM_FILE:
	     mImageCaptureUri = data.getData();

             doCrop();

             break;

Line 10: After taking a picture, do the crop
Line 6: After selecting image from files, save the selected path

private void doCrop() {
		final ArrayList<CropOption> cropOptions = new ArrayList<CropOption>();

    	Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setType("image/*");

        List<ResolveInfo> list = getPackageManager().queryIntentActivities( intent, 0 );

        int size = list.size();

        if (size == 0) {
        	Toast.makeText(this, "Can not find image crop app", Toast.LENGTH_SHORT).show();

            return;
        } else {
        	intent.setData(mImageCaptureUri);

            intent.putExtra("outputX", 200);
            intent.putExtra("outputY", 200);
            intent.putExtra("aspectX", 1);
            intent.putExtra("aspectY", 1);
            intent.putExtra("scale", true);
            intent.putExtra("return-data", true);

        	if (size == 1) {
        		Intent i 		= new Intent(intent);
	        	ResolveInfo res	= list.get(0);

	        	i.setComponent( new ComponentName(res.activityInfo.packageName, res.activityInfo.name));

	        	startActivityForResult(i, CROP_FROM_CAMERA);
        	} else {
		        for (ResolveInfo res : list) {
		        	final CropOption co = new CropOption();

		        	co.title 	= getPackageManager().getApplicationLabel(res.activityInfo.applicationInfo);
		        	co.icon		= getPackageManager().getApplicationIcon(res.activityInfo.applicationInfo);
		        	co.appIntent= new Intent(intent);

		        	co.appIntent.setComponent( new ComponentName(res.activityInfo.packageName, res.activityInfo.name));

		            cropOptions.add(co);
		        }

		        CropOptionAdapter adapter = new CropOptionAdapter(getApplicationContext(), cropOptions);

		        AlertDialog.Builder builder = new AlertDialog.Builder(this);
		        builder.setTitle("Choose Crop App");
		        builder.setAdapter( adapter, new DialogInterface.OnClickListener() {
		            public void onClick( DialogInterface dialog, int item ) {
		                startActivityForResult( cropOptions.get(item).appIntent, CROP_FROM_CAMERA);
		            }
		        });

		        builder.setOnCancelListener( new DialogInterface.OnCancelListener() {
		            @Override
		            public void onCancel( DialogInterface dialog ) {

		                if (mImageCaptureUri != null ) {
		                    getContentResolver().delete(mImageCaptureUri, null, null );
		                    mImageCaptureUri = null;
		                }
		            }
		        } );

		        AlertDialog alert = builder.create();

		        alert.show();
        	}
        }
	}

Line 4: Open image crop app by starting an intent ‘com.android.camera.action.CROP‘.
Line 7: Check if there is image cropper app installed.
Line 11: If there is no image cropper app, display warning message
Line 16-23: Specify the image path, crop dimension and scale
Line 25: There is posibility when more than one image cropper app exist, so we have to check for it first. If there is only one app, open then app.
Line 33-68. If there are several app exist, create a custom chooser to let user selects the app.

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

	    switch (requestCode) {

		    case CROP_FROM_CAMERA:
		        Bundle extras = data.getExtras();

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

		            mImageView.setImageBitmap(photo);
		        }

		        File f = new File(mImageCaptureUri.getPath());

		        if (f.exists()) f.delete();

		        break;

Line 11: After cropping the image, get the bitmap of the cropped image and display it on imageview.
Line 16: Delete the temporary image

Download source code (github)

Share
Related post:
bottom

63 Responses to “How to Select and Crop Image on Android”

  1. tom says:

    hi
    thanks for the usefull post. but how can i use the cropped picture in other classes?
    thanks again

  2. Geetanjali says:

    after cropping the image and there are two buttons SAVE and DISCARD. so on clicking save i want to save it in the SD card how can i do that?please hepl me in doing that?

    • lorenz says:

      Hi,

      look at onActivityResult(int requestCode, int resultCode, Intent data),crop app returns bitmap of cropped image, you can save it on sdcard.

      switch (requestCode) {

      case CROP_FROM_CAMERA:
      Bundle extras = data.getExtras();

      if (extras != null) {
      Bitmap photo = extras.getParcelable(”data”); //save this bitmap into sdcard….
      saveBitmapToFile(”/sdcard/cropped_img.jpg”, photo);

      }

      //method to save bitmap
      public boolean saveBitmapToFile(String path, Bitmap bitmap) {
      File file = new File(path);
      boolean res = false;

      if (!file.exists()) {
      try {
      FileOutputStream fos = new FileOutputStream(file);

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

      fos.close();
      } catch (Exception e) { }
      }

      return res;
      }

      • Anita says:

        can any one tell me how to convert image in to pdf format in android

        • midhun says:

          /*
          * Copyright (C) 2011 The ADMMS OCR Project
          *
          * Licensed under the Apache License, Version 2.0 (the “License”);
          * you may not use this file except in compliance with the License.
          * You may obtain a copy of the License at
          *
          * http://www.apache.org/licenses/LICENSE-2.0
          *
          * Unless required by applicable law or agreed to in writing, software
          * distributed under the License is distributed on an “AS IS” BASIS,
          * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
          * See the License for the specific language governing permissions and
          * limitations under the License.
          */

          package packag;

          import com.itextpdf.text.Document;
          import com.itextpdf.text.Paragraph;
          import com.itextpdf.text.pdf.PdfWriter;
          import java.io.File;
          import java.io.FileOutputStream;
          /**
          *
          * @author midhun
          *
          */
          public class PDFConversion
          {
          /*
          * This method is used to convert the given file to a PDF format
          * @param inputFile – Name and the path of the file
          * @param outputFile – Name and the path where the PDF file to be saved
          * @param isPictureFile
          */
          private void createPdf(String inputFile, String outputFile, boolean isPictureFile)
          {
          /**
          * Create a new instance for Document class
          */
          Document pdfDocument = new Document();
          String pdfFilePath = outputFile;
          try
          {
          FileOutputStream fileOutputStream = new FileOutputStream(pdfFilePath);
          PdfWriter writer = null;
          writer = PdfWriter.getInstance(pdfDocument, fileOutputStream);
          writer.open();
          pdfDocument.open();
          /**
          * Proceed if the file given is a picture file
          */
          if (isPictureFile)
          {
          pdfDocument.add(com.itextpdf.text.Image.getInstance(inputFile));
          }
          /**
          * Proceed if the file given is (.txt,.html,.doc etc)
          */
          else
          {
          File file = new File(inputFile);
          pdfDocument.add(new Paragraph(org.apache.commons.io.FileUtils.readFileToString(file, null )));
          }

          pdfDocument.close();
          writer.close();
          }
          catch (Exception exception)
          {
          System.out.println(”Document Exception!” + exception);
          }
          }

          public static void main(String args[])
          {
          PDFConversion pdfConversion = new PDFConversion();
          pdfConversion.createPdf(”C:/Users/Administrator/Desktop/mk.png”, “C:/Users/Administrator/Desktop/mk.pdf”, true);

          }
          }

          /* include commons-io-1.1.jar and itextpdf-5.2.0.jar in external libraries */

  3. Geetanjali says:

    hey i have save my image taken from camera in SD card nad when i use that path for showing image its null.where the problem actually is?

  4. Geetanjali says:

    hello Lorenz

    I have made an activity that pick image from gallery and capture a new image from camera.and i m storing both in SD card using putExtra(MediaStore.EXTRA_OUTPUT,filepath)
    but its showing null pointer Exception when accesing that path to show that image.problem may be its not saving that image to specified path.

    here is ma code…..
    public void onClick(DialogInterface dialog, int item)
    {
    Intent intent = new Intent();
    intent.putExtra(”crop”, “true”);
    intent.putExtra(”aspectX”, 730);
    intent.putExtra(”aspectY”, 1115);
    intent.putExtra(”outputX”, 730);
    intent.putExtra(”outputY”, 1115);
    intent.putExtra(MediaStore.EXTRA_OUTPUT, getTempFile());
    intent.putExtra(”outputFormat”, Bitmap.CompressFormat.JPEG.toString());
    if(item==0)
    {
    intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
    startActivityForResult(intent, PICK_FROM_CAMERA);
    }
    else if(item==1)
    {
    intent.setAction(Intent.ACTION_PICK);
    intent.setType(”image/*”);
    startActivityForResult(intent, SELECT_PICTURE);
    }
    }
    private Uri getTempFile()
    {
    muri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(),”Image_” + ++count + “.jpg”));
    return muri;
    }
    });
    final AlertDialog alert = builder.create();
    ((Button) findViewById(R.id.button)).setOnClickListener(new OnClickListener()
    {
    @Override
    public void onClick(View view)
    {
    alert.show();
    }
    });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data)
    {
    super.onActivityResult(requestCode, resultCode, data);

    switch(requestCode)
    {
    case PICK_FROM_CAMERA : if (resultCode == RESULT_OK)
    {
    String filePath= muri.getPath();
    Toast.makeText(this, filePath, Toast.LENGTH_SHORT).show();
    Bitmap selectedImage = BitmapFactory.decodeFile(filePath);
    ImageView image = (ImageView)findViewById(R.id.selectedimage);
    image.setImageBitmap(selectedImage);
    }
    break;
    case SELECT_PICTURE : if (resultCode == RESULT_OK)
    {
    String filePath= muri.getPath();
    Toast.makeText(this, filePath, Toast.LENGTH_SHORT).show();
    Bitmap selectedImage = BitmapFactory.decodeFile(filePath);
    ImageView image = (ImageView)findViewById(R.id.selectedimage);
    image.setImageBitmap(selectedImage);
    }
    break;
    default:
    break;
    }
    }

  5. Geetanjali says:

    I have solved my problem.anyways thanks for ur support

  6. Geetanjali says:

    sory I have deleted that.hey just help me I have given the aspect ratios in intent.but it’s not showing it.How to do that?as it is cropping but not taking aspect ratio?Why is this happening?

  7. Anne says:

    Thank you for the great example. It works very well. I have one problem though. Even though I am specifying EXTRA_OUTPUT for the image capture (the cropped image is being successfully saved where I specify), the uncropped image is also being saved on the sd card in the camera’s default save location \dcim in both the \.thumbnails and \Camera directories. How can I prevent the image from also being saved to the Camera default directories?

  8. h4mzy says:

    hi, lorenz.

    can i remove save/button so after i take a picture it always save to sdcard.

  9. piet in het veld says:

    Would it be possible to crop rectangles instead of only squares? Now, if I move one side the adjacent side moves along, keeping it a square selection.

  10. Pankaj says:

    Hi,
    Thanks for your such nice code.
    Same code is working in Table but i m surprised it is not working in xperia device. Galary crop is working fine but camera photo crop is not working. When i m taking photo then crop option should come but i m not getting that option. I m sending few logcat part. Plz find in below.
    Please suggest me what is the problem. I need ur help to fix this issue.
    Thanks a lot.

    10-28 21:27:29.255: INFO/NotificationService(1141): enqueueToast pkg=com.sonyericsson.android.camera callback=android.app.ITransientNotification$Stub$Proxy@45cdea58 duration=0
    10-28 21:27:29.275: ERROR/SemcCameraApp(5351): ViewFinderController:onExternalMemoryStatusChanged( 0 )
    10-28 21:27:29.355: WARN/AudioService(1141): stream was not muted by this client
    10-28 21:27:29.355: ERROR/AudioService(1141): Could not get client death handler for stream: 5
    10-28 21:27:29.355: ERROR/SemcCameraApp(5351): VideoController:releaseMediaRecorder: mVideoDevice is null.
    10-28 21:27:29.365: DEBUG/CameraService(1067): stopPreview (pid 5351)
    10-28 21:27:29.365: DEBUG/CameraService(1067): stopPreview(), hardware stopped OK
    10-28 21:27:29.395: DEBUG/CameraService(1067): Client::disconnect() E (pid 5351 client 0×451e0)
    10-28 21:27:29.395: DEBUG/CameraService(1067): hardware teardown
    10-28 21:27:29.455: DEBUG/CameraService(1067): removeClient (pid 5351) done
    10-28 21:27:29.455: DEBUG/CameraService(1067): Client::disconnect() X (pid 5351)
    10-28 21:27:29.455: DEBUG/dalvikvm(5351): threadid=17 wakeup: interrupted
    10-28 21:27:29.465: DEBUG/CameraService(1067): Client::~Client E (pid 1067, client 0×451e0)
    10-28 21:27:29.465: INFO/ActivityManager(1141): Start proc com.sonyericsson.android.timescape for broadcast com.sonyericsson.android.timescape/.Spline.receiver.TimescapeCpRefreshReceiver: pid=5393 uid=10011 gids={3003, 1015}
    10-28 21:27:29.475: INFO/ActivityManager(1141): Starting activity: Intent { act=com.android.camera.action.CROP dat=file:///sdcard/tmp_avatar_1319817437350.jpg cmp=com.cooliris.media/.CropImage (has extras) }
    10-28 21:27:29.565: DEBUG/CameraService(1067): Client::disconnect() E (pid 1067 client 0×451e0)
    10-28 21:27:29.565: DEBUG/CameraService(1067): Client::~Client X (pid 1067)
    10-28 21:27:29.605: ERROR/UriTexture(1816): Error loading image from uri file:///sdcard/tmp_avatar_1319817437350.jpg
    10-28 21:27:29.605: ERROR/CropImage(1816): Cannot load bitmap, exiting.
    10-28 21:27:29.695: INFO/dalvikvm(5393): Debugger thread not active, ignoring DDM send (t=0×41504e4d l=38)
    10-28 21:27:29.725: INFO/dalvikvm(5393): Debugger thread not active, ignoring DDM send (t=0×41504e4d l=72)

    • lorenz says:

      Hi,

      That means the camera app didn’t write the output into temporary file.

      mImageCaptureUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(),
      “tmp_avatar_” + String.valueOf(System.currentTimeMillis()) + “.jpg”) –>

      So you got this error:

      10-28 21:27:29.565: DEBUG/CameraService(1067): Client::~Client X (pid 1067)
      10-28 21:27:29.605: ERROR/UriTexture(1816): Error loading image from uri file:///sdcard/tmp_avatar_1319817437350.jpg
      10-28 21:27:29.605: ERROR/CropImage(1816): Cannot load bitmap, exiting.

      I think this bug is specific to some camera vendor, take a look at this discussion, it may helps you:

      http://stackoverflow.com/questions/1910608/android-action-image-capture-intent

    • Yogesh says:

      I also had the same problem. But with a little debugging, I noticed that if I add a small delay (50ms) before doCrop() call, it works fine. In my case, theh problem was that doCrop was being called before the camera app could finish saving the new image file and hence the NULL pointer. After adding this small delay it worked fine for me.

  11. Once again great example- saved time and worked without problems.

  12. Site Status says:

    Works fine for me. Thanks.

  13. made says:

    i’ve got some problem during implementing your code in my device, i’ve got se x8 device.
    when i select from camera i got this error show in logcat :

    “Ketika crop dari camera

    10-29 22:51:08.557: ERROR/AndroidRuntime(522): FATAL EXCEPTION: main
    10-29 22:51:08.557: ERROR/AndroidRuntime(522): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.cooliris.media/com.cooliris.media.CropImage}: java.lang.NullPointerException
    10-29 22:51:08.557: ERROR/AndroidRuntime(522): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1768)
    10-29 22:51:08.557: ERROR/AndroidRuntime(522): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1784)
    10-29 22:51:08.557: ERROR/AndroidRuntime(522): at android.app.ActivityThread.access$1500(ActivityThread.java:123)
    10-29 22:51:08.557: ERROR/AndroidRuntime(522): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:939)
    10-29 22:51:08.557: ERROR/AndroidRuntime(522): at android.os.Handler.dispatchMessage(Handler.java:99)
    10-29 22:51:08.557: ERROR/AndroidRuntime(522): at android.os.Looper.loop(Looper.java:130)
    10-29 22:51:08.557: ERROR/AndroidRuntime(522): at android.app.ActivityThread.main(ActivityThread.java:3835)
    10-29 22:51:08.557: ERROR/AndroidRuntime(522): at java.lang.reflect.Method.invokeNative(Native Method)
    10-29 22:51:08.557: ERROR/AndroidRuntime(522): at java.lang.reflect.Method.invoke(Method.java:507)
    10-29 22:51:08.557: ERROR/AndroidRuntime(522): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:847)
    10-29 22:51:08.557: ERROR/AndroidRuntime(522): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:605)
    10-29 22:51:08.557: ERROR/AndroidRuntime(522): at dalvik.system.NativeStart.main(Native Method)
    10-29 22:51:08.557: ERROR/AndroidRuntime(522): Caused by: java.lang.NullPointerException
    10-29 22:51:08.557: ERROR/AndroidRuntime(522): at com.cooliris.media.CropImage.onCreate(CropImage.java:263)
    10-29 22:51:08.557: ERROR/AndroidRuntime(522): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
    10-29 22:51:08.557: ERROR/AndroidRuntime(522): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1722)
    10-29 22:51:08.557: ERROR/AndroidRuntime(522): … 11 more

    and this when i pick from galery :
    “Logcat ketika crop dari galery
    10-29 22:55:03.127: ERROR/AndroidRuntime(737): FATAL EXCEPTION: main
    10-29 22:55:03.127: ERROR/AndroidRuntime(737): java.lang.RuntimeException: Unable to resume activity {net.londatiga.android/net.londatiga.android.MainActivity}: java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=2, result=-1, data=Intent { act=inline-data (has extras) }} to activity {net.londatiga.android/net.londatiga.android.MainActivity}: java.lang.NullPointerException
    10-29 22:55:03.127: ERROR/AndroidRuntime(737): at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2241)
    10-29 22:55:03.127: ERROR/AndroidRuntime(737): at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2256)
    10-29 22:55:03.127: ERROR/AndroidRuntime(737): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1789)
    10-29 22:55:03.127: ERROR/AndroidRuntime(737): at android.app.ActivityThread.access$1500(ActivityThread.java:123)
    10-29 22:55:03.127: ERROR/AndroidRuntime(737): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:939)
    10-29 22:55:03.127: ERROR/AndroidRuntime(737): at android.os.Handler.dispatchMessage(Handler.java:99)
    10-29 22:55:03.127: ERROR/AndroidRuntime(737): at android.os.Looper.loop(Looper.java:130)
    10-29 22:55:03.127: ERROR/AndroidRuntime(737): at android.app.ActivityThread.main(ActivityThread.java:3835)
    10-29 22:55:03.127: ERROR/AndroidRuntime(737): at java.lang.reflect.Method.invokeNative(Native Method)
    10-29 22:55:03.127: ERROR/AndroidRuntime(737): at java.lang.reflect.Method.invoke(Method.java:507)
    10-29 22:55:03.127: ERROR/AndroidRuntime(737): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:847)
    10-29 22:55:03.127: ERROR/AndroidRuntime(737): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:605)
    10-29 22:55:03.127: ERROR/AndroidRuntime(737): at dalvik.system.NativeStart.main(Native Method)
    10-29 22:55:03.127: ERROR/AndroidRuntime(737): Caused by: java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=2, result=-1, data=Intent { act=inline-data (has extras) }} to activity {net.londatiga.android/net.londatiga.android.MainActivity}: java.lang.NullPointerException
    10-29 22:55:03.127: ERROR/AndroidRuntime(737): at android.app.ActivityThread.deliverResults(ActivityThread.java:2653)
    10-29 22:55:03.127: ERROR/AndroidRuntime(737): at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2228)
    10-29 22:55:03.127: ERROR/AndroidRuntime(737): … 12 more
    10-29 22:55:03.127: ERROR/AndroidRuntime(737): Caused by: java.lang.NullPointerException
    10-29 22:55:03.127: ERROR/AndroidRuntime(737): at net.londatiga.android.MainActivity.onActivityResult(MainActivity.java:117)
    10-29 22:55:03.127: ERROR/AndroidRuntime(737): at android.app.Activity.dispatchActivityResult(Activity.java:3908)
    10-29 22:55:03.127: ERROR/AndroidRuntime(737): at android.app.ActivityThread.deliverResults(ActivityThread.java:2649)
    10-29 22:55:03.127: ERROR/AndroidRuntime(737): … 13 more

    the picture was successfully taken within this app and saved in my sdcard.

    can you help me explain what i’ve got here?

  14. Harsha M V says:

    Lorenz,

    Thanks for the tutorial. I have been trying to implement the code into my project. when i choose an image from Gallery and when it has to open the cropping application the application crashes.

    Error
    10-31 02:20:10.565: E/AndroidRuntime(15847): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.cooliris.media/com.cooliris.media.CropImage}: java.lang.NullPointerException

    i have posted the question on StackOVerFlow with more details and code
    http://stackoverflow.com/questions/7947712/android-image-cropping-error

    Hope the code was enuf for you to understand whats going wrong.

    • Lorenz says:

      You’re welcome Harsha,

      That means crop app was not available on your Android phone (null pointer). But, that’s quite strange, android managed to resolve crop app and found com.coolirils.media but it could not be started and not found. What android version & phone model did u use?

  15. Pavan says:

    After cropping there are ‘Save’ & ‘Discard’ buttons. How can I change the text on the button? Say, to ‘Done’ & ‘Cancel’.

  16. Mukesh says:

    Hi Lorez,

    A Question on Cropping. When i try cropping an image after taking a pic, it shows a rectangle, When i try seleting area or object,the other sides of the Rectangle gets resized which i dont wanted. can you please help me in that.

  17. Faysal says:

    Hi … i want to launched this Crop Activity(MainActivity) on Button But when i Press Button app stopped unexpectedly …
    log cat error : 11-06 16:34:20.778: ERROR/AndroidRuntime(296): FATAL EXCEPTION: main 11-06 16:34:20.778: ERROR/AndroidRuntime(296): java.lang.IllegalStateException: Could not execute method of the activit

  18. Amelia says:

    thanks for your tutorial..
    how if I want to crop image not from uri, but from created bitmap?

  19. Boogie says:

    Thank you very much for the tutorial.
    Your code is so clean and able to understand.
    You are a hell of a android developer!!

  20. Kush says:

    Thanks for the tutorial, really nice work save time for me.

  21. aashish says:

    hi this is a gr8 tutorial I am using this from a long time however it is behaving strangely now that I am using it on 2.2.1

    it opens image for cropping in landscape orientation but crashes in potrait

    I get null pointer exception in CropImage Thread-9

    • @nudeep says:

      aashish:
      I am facing a problem on cropping the image in ovel shape if u know that pls share it …
      Thks in advance…

  22. aashish says:

    working great for gallery image cropping

  23. Zalak says:

    hi,
    I tried to implement your code its working fine when implemented with single java file.
    But when I am trying to implement the same code using 2 java files wherein from one java file I have to just call the function say selectimagefromfile()and set the image url and All the processing is done in other java file…
    Now on implementing this I am getting a null pointer on startActivityForResult(Intent.createChooser(intent,”Complete action using”), PICK_FROM_FILE);

    How do I resolve this..

  24. Jenny says:

    Thanks for your tutorial.
    Very clean and understandable code.

    The app works very well on android 2.3. it doesn’t save the crop image on android 2.2 and 4.0

    I don’t have devices for debugging the problem.

  25. Kumarvarma says:

    Thanks for your great tutorial.

    I am testing this application on 2.3 and 2.3.3 and below of 2.2 also it’s working fine but it’s not working in 2.2 it’s getting force close error.can you please solve my problem.

    like:
    03-09 10:58:19.713: E/AndroidRuntime(468): java.lang.IllegalArgumentException: No configs match configSpec

    03-09 10:58:19.713: E/AndroidRuntime(468): at android.opengl.GLSurfaceView$BaseConfigChooser.chooseConfig(GLSurfaceView.java:760)

    03-09 10:58:19.713: E/AndroidRuntime(468): at android.opengl.GLSurfaceView$EglHelper.start(GLSurfaceView.java:916)

    03-09 10:58:19.713: E/AndroidRuntime(468): at android.opengl.GLSurfaceView$GLThread.guardedRun(GLSurfaceView.java:1246)

    03-09 10:58:19.713: E/AndroidRuntime(468): at android.opengl.GLSurfaceView$GLThread.run(GLSurfaceView.java:1116)

    Thanks
    =====
    KK

  26. harsh says:

    Hi
    I need code which cropping images and set as wallpaper.

    All images comes from web service.

    I have made one app which display all iamges when user select any one then i creaet new page where user crop that and set as wall paper but functioanlity works but not getting correct resolution.

    Please help me.

  27. Anita says:

    how to convert image in to pdf format in android?

  28. NItesh says:

    hello, i am trying to crop image respecting the size of the screen but when i try to pass rectangle dimensions, onActivityResult() is not called! …selecting image from camera and gallery is working.

    intent.setData(mImageCaptureUri);
    DisplayMetrics dm = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(dm);
    int width = dm.widthPixels;
    int height = dm.heightPixels;
    System.out.println(width+" "+height);

    intent.putExtra("outputX", width);
    intent.putExtra("outputY", height);
    intent.putExtra("aspectX", width);
    intent.putExtra("aspectY", height);
    intent.putExtra("scale", true);
    intent.putExtra("return-data", true);

    Please help

  29. Shahnawaz says:

    I am using this code fro the Samsung gallaxy and it is working purfectly fine but it is not working properly on the htc wildfire. I think it is not saving the image properly. for that i need to pass a bitmap to the croping winodw instead of using the uri of an image can i have a suggestion about that please….

  30. $urya says:

    hi any one know how crop an image as ovel shape can u help me for this….

  31. Alireza says:

    Thank you very much Lorenz,
    Great example and nice tutorial, You saved my time,
    Greeting from Iran.

  32. Philisia says:

    I have already select an image. I want to crop that image and after cropping i want that image to show in my app. Is this possible?

  33. Atul says:

    Thanx Alot………………..

  34. @nudeep says:

    Haiii ,its very use full tutorial . i am facing one problem here.
    1. In this tutorial when the save button click its will store in sdcard but can we customize the location where it should been stored??where we change the code??
    2. can i want customize the camera preview, is it possible??
    3. important for me. when the crop image is done can i render the same image into my activity ??how??suppose i use to crop my face and i need to use the face into my customize frame ….i am struggling here if u know plz share it…

    if u have any example of how to render the image from one activity to another activity?? pls share the links…
    Thks in advance..:)

  35. Philisia says:

    Please help me. I am doing an application which has many picture editing facilities. one of them is crop. So can I crop the image of my application which is already picked from camera. So I don’t need to pick from Camera or Gallery I just want to crop the image by the given code. I want to skip the picking feature. Please help me how can CROP my image and after cropping get that cropped image into my application…
    Please please help me

  36. Philisia says:

    @nudeep :
    Problem no 3:Render the image from one activity to another activity
    ——————————————-
    Make a class like this ->

    public class PhotoFeature
    {
    static Bitmap original_image = null;

    public static Bitmap getphoto()
    {
    return current_image;
    }
    public static void setphoto(Bitmap image)
    {
    current_image = image;
    }
    Now in
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode != RESULT_OK) return;

    switch (requestCode) {

    case CROP_FROM_CAMERA:
    Bundle extras = data.getExtras();
    if (extras != null) {
    Bitmap photo = extras.getParcelable(”data”);
    mImageView.setImageBitmap(photo);
    PhotoFeature.setphoto(photo);
    }
    In your activity call PhotoFeature.getphoto(photo);

    That’s it..

  37. Philisia says:

    Define PhotoFeature class in your app. And onActivityResult(a,a,a).. is in the above code …

  38. @nudeep says:

    Philisia :
    Thks for u’r reply…can u help me to crop the the image in ovel shape …in my current project i need to crop the exact face and render the crop image into my activity and need to place into my frame ….

  39. @nudeep says:

    can anybody help me how to crop the the image in ovel shape …
    or
    on my current project i need to crop the exact face and render the crop image into my activity and need to place into my frame ….

    or is their any way to render the exact face in my activity????

    Thks in advance…

  40. @nudeep says:

    Is their any way to crop the exact face on cropping image????

    anybody????

  41. Ajay Kumar says:

    Please can tell me how to find the height and weight of crop images. I am try for many days.

  42. Ashish says:

    Hey lorenz , Gr8 tutorial and thanks for sharing the code .

    I’m not able post the cropped image from Gallery to server , it sends an original image but when I’m using camera ,everything works fine .

    snippets>
    case PICK_FROM_CAMERA:
    if (resultCode == RESULT_OK)
    {
    String filePath= mImageCaptureUri.getPath();
    photo = BitmapFactory.decodeFile(filePath);
    //Bitmap resultGreen = invert(photo);
    mImageView.setImageBitmap(photo);
    }
    doCrop();
    break;

    case PICK_FROM_FILE:
    if(resultCode == RESULT_OK){
    mImageCaptureUri = data.getData();
    String filePath = getRealPathFromURI(mImageCaptureUri);
    photo = BitmapFactory.decodeFile(filePath);
    mImageView.setImageBitmap(photo);
    }

    doCrop();
    break ;

  43. Ashish says:

    Hey lorenz , I want to add an image filter buttons at ImageCrop Intent .
    How can I add it ??

  44. praveen says:

    Hi lorenz, i really like the way you explained and given every thing to implement the same. and also your responsiveness to the posted comments. I appreciate you for every thing…

    Thank you so much… your site helped me a lot….

    I just like to know this code supports on all devices…. or i need to implement a customized camera screen.. to support on all devices….

Leave a Reply

 
bottom