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

<br /><%%KEEPWHITESPACE%%> final String [] items	      = new String [] {"Take from camera", "Select from Gallery"};<br /><%%KEEPWHITESPACE%%> ArrayAdapter&lt;String&gt; adapter = new ArrayAdapter&lt;String&gt; (this, android.R.layout.select_dialog_item,items);<br /><%%KEEPWHITESPACE%%> AlertDialog.Builder builder  = new AlertDialog.Builder(this);<br /><br /><%%KEEPWHITESPACE%%> builder.setTitle("Select Image");<br /><%%KEEPWHITESPACE%%> builder.setAdapter( adapter, new DialogInterface.OnClickListener() {<br /><%%KEEPWHITESPACE%%>    public void onClick( DialogInterface dialog, int item ) { //pick from camer<br /><%%KEEPWHITESPACE%%>	if (item == 0) {<br /><%%KEEPWHITESPACE%%>	    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);<br /><br /><%%KEEPWHITESPACE%%>	    mImageCaptureUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(),<br /><%%KEEPWHITESPACE%%>				 "tmp_avatar_" + String.valueOf(System.currentTimeMillis()) + ".jpg"));<br /><br /><%%KEEPWHITESPACE%%>	    intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, mImageCaptureUri);<br /><br /><%%KEEPWHITESPACE%%>	    try {<br /><%%KEEPWHITESPACE%%>		intent.putExtra("return-data", true);<br /><br /><%%KEEPWHITESPACE%%>		startActivityForResult(intent, PICK_FROM_CAMERA);<br /><%%KEEPWHITESPACE%%>	    } catch (ActivityNotFoundException e) {<br /><%%KEEPWHITESPACE%%>		e.printStackTrace();<br /><%%KEEPWHITESPACE%%>	    }<br /><%%KEEPWHITESPACE%%>       } else { //pick from file<br /><%%KEEPWHITESPACE%%>	   Intent intent = new Intent();<br /><br /><%%KEEPWHITESPACE%%>	   intent.setType("image/*");<br /><%%KEEPWHITESPACE%%>	   intent.setAction(Intent.ACTION_GET_CONTENT);<br /><br /><%%KEEPWHITESPACE%%>	   startActivityForResult(Intent.createChooser(intent, "Complete action using"), PICK_FROM_FILE);<br /><%%KEEPWHITESPACE%%>       }<br /><%%KEEPWHITESPACE%%>    }<br /><%%KEEPWHITESPACE%%> } );<br /><br />final AlertDialog dialog = builder.create();<br /><br />Button button 	= (Button) findViewById(R.id.btn_crop);<br />mImageView	= (ImageView) findViewById(R.id.iv_photo);<br /><br />button.setOnClickListener(new View.OnClickListener() {<br /><%%KEEPWHITESPACE%%>   @Override<br /><%%KEEPWHITESPACE%%>   public void onClick(View v) {<br /><%%KEEPWHITESPACE%%>	dialog.show();<br /><%%KEEPWHITESPACE%%>   }<br />});<br />

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.

<br />@Override<br />protected void onActivityResult(int requestCode, int resultCode, Intent data) {<br /><%%KEEPWHITESPACE%%>   if (resultCode != RESULT_OK) return;<br /><%%KEEPWHITESPACE%%>       switch (requestCode) {<br /><%%KEEPWHITESPACE%%>          case PICK_FROM_CAMERA:<br /><%%KEEPWHITESPACE%%>	     doCrop();<br /><%%KEEPWHITESPACE%%>             break;<br /><br /><%%KEEPWHITESPACE%%>          case PICK_FROM_FILE:<br /><%%KEEPWHITESPACE%%>	     mImageCaptureUri = data.getData();<br /><br /><%%KEEPWHITESPACE%%>             doCrop();<br /><br /><%%KEEPWHITESPACE%%>             break;<br />

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

<br />private void doCrop() {<br /><%%KEEPWHITESPACE%%>		final ArrayList&lt;CropOption&gt; cropOptions = new ArrayList&lt;CropOption&gt;();<br /><br /><%%KEEPWHITESPACE%%>    	Intent intent = new Intent("com.android.camera.action.CROP");<br /><%%KEEPWHITESPACE%%>        intent.setType("image/*");<br /><br /><%%KEEPWHITESPACE%%>        List&lt;ResolveInfo&gt; list = getPackageManager().queryIntentActivities( intent, 0 );<br /><br /><%%KEEPWHITESPACE%%>        int size = list.size();<br /><br /><%%KEEPWHITESPACE%%>        if (size == 0) {<br /><%%KEEPWHITESPACE%%>        	Toast.makeText(this, "Can not find image crop app", Toast.LENGTH_SHORT).show();<br /><br /><%%KEEPWHITESPACE%%>            return;<br /><%%KEEPWHITESPACE%%>        } else {<br /><%%KEEPWHITESPACE%%>        	intent.setData(mImageCaptureUri);<br /><br /><%%KEEPWHITESPACE%%>            intent.putExtra("outputX", 200);<br /><%%KEEPWHITESPACE%%>            intent.putExtra("outputY", 200);<br /><%%KEEPWHITESPACE%%>            intent.putExtra("aspectX", 1);<br /><%%KEEPWHITESPACE%%>            intent.putExtra("aspectY", 1);<br /><%%KEEPWHITESPACE%%>            intent.putExtra("scale", true);<br /><%%KEEPWHITESPACE%%>            intent.putExtra("return-data", true);<br /><br /><%%KEEPWHITESPACE%%>        	if (size == 1) {<br /><%%KEEPWHITESPACE%%>        		Intent i 		= new Intent(intent);<br /><%%KEEPWHITESPACE%%>	        	ResolveInfo res	= list.get(0);<br /><br /><%%KEEPWHITESPACE%%>	        	i.setComponent( new ComponentName(res.activityInfo.packageName, res.activityInfo.name));<br /><br /><%%KEEPWHITESPACE%%>	        	startActivityForResult(i, CROP_FROM_CAMERA);<br /><%%KEEPWHITESPACE%%>        	} else {<br /><%%KEEPWHITESPACE%%>		        for (ResolveInfo res : list) {<br /><%%KEEPWHITESPACE%%>		        	final CropOption co = new CropOption();<br /><br /><%%KEEPWHITESPACE%%>		        	co.title 	= getPackageManager().getApplicationLabel(res.activityInfo.applicationInfo);<br /><%%KEEPWHITESPACE%%>		        	co.icon		= getPackageManager().getApplicationIcon(res.activityInfo.applicationInfo);<br /><%%KEEPWHITESPACE%%>		        	co.appIntent= new Intent(intent);<br /><br /><%%KEEPWHITESPACE%%>		        	co.appIntent.setComponent( new ComponentName(res.activityInfo.packageName, res.activityInfo.name));<br /><br /><%%KEEPWHITESPACE%%>		            cropOptions.add(co);<br /><%%KEEPWHITESPACE%%>		        }<br /><br /><%%KEEPWHITESPACE%%>		        CropOptionAdapter adapter = new CropOptionAdapter(getApplicationContext(), cropOptions);<br /><br /><%%KEEPWHITESPACE%%>		        AlertDialog.Builder builder = new AlertDialog.Builder(this);<br /><%%KEEPWHITESPACE%%>		        builder.setTitle("Choose Crop App");<br /><%%KEEPWHITESPACE%%>		        builder.setAdapter( adapter, new DialogInterface.OnClickListener() {<br /><%%KEEPWHITESPACE%%>		            public void onClick( DialogInterface dialog, int item ) {<br /><%%KEEPWHITESPACE%%>		                startActivityForResult( cropOptions.get(item).appIntent, CROP_FROM_CAMERA);<br /><%%KEEPWHITESPACE%%>		            }<br /><%%KEEPWHITESPACE%%>		        });<br /><br /><%%KEEPWHITESPACE%%>		        builder.setOnCancelListener( new DialogInterface.OnCancelListener() {<br /><%%KEEPWHITESPACE%%>		            @Override<br /><%%KEEPWHITESPACE%%>		            public void onCancel( DialogInterface dialog ) {<br /><br /><%%KEEPWHITESPACE%%>		                if (mImageCaptureUri != null ) {<br /><%%KEEPWHITESPACE%%>		                    getContentResolver().delete(mImageCaptureUri, null, null );<br /><%%KEEPWHITESPACE%%>		                    mImageCaptureUri = null;<br /><%%KEEPWHITESPACE%%>		                }<br /><%%KEEPWHITESPACE%%>		            }<br /><%%KEEPWHITESPACE%%>		        } );<br /><br /><%%KEEPWHITESPACE%%>		        AlertDialog alert = builder.create();<br /><br /><%%KEEPWHITESPACE%%>		        alert.show();<br /><%%KEEPWHITESPACE%%>        	}<br /><%%KEEPWHITESPACE%%>        }<br /><%%KEEPWHITESPACE%%>	}<br />

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.

<br />@Override<br /><%%KEEPWHITESPACE%%>	protected void onActivityResult(int requestCode, int resultCode, Intent data) {<br /><%%KEEPWHITESPACE%%>	    if (resultCode != RESULT_OK) return;<br /><br /><%%KEEPWHITESPACE%%>	    switch (requestCode) {<br /><br /><%%KEEPWHITESPACE%%>		    case CROP_FROM_CAMERA:<br /><%%KEEPWHITESPACE%%>		        Bundle extras = data.getExtras();<br /><br /><%%KEEPWHITESPACE%%>		        if (extras != null) {<br /><%%KEEPWHITESPACE%%>		            Bitmap photo = extras.getParcelable("data");<br /><br /><%%KEEPWHITESPACE%%>		            mImageView.setImageBitmap(photo);<br /><%%KEEPWHITESPACE%%>		        }<br /><br /><%%KEEPWHITESPACE%%>		        File f = new File(mImageCaptureUri.getPath());<br /><br /><%%KEEPWHITESPACE%%>		        if (f.exists()) f.delete();<br /><br /><%%KEEPWHITESPACE%%>		        break;<br /><br />

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)

facebooktwittergoogle_plusredditpinterestlinkedinmailby feather

Comments

  1. 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?

    • 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;
      }

        • 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 */

  2. 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?

  3. 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;
    }
    }

  4. 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?

  5. 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?

  6. 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.

  7. 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 0x451e0)
    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 0x451e0)
    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 0x451e0)
    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=0x41504e4d l=38)
    10-28 21:27:29.725: INFO/dalvikvm(5393): Debugger thread not active, ignoring DDM send (t=0x41504e4d l=72)

    • 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.

  8. 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?

  9. 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.

    • 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?

  10. Pavan says

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

  11. 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.

  12. 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

  13. 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!!

  14. 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…

  15. 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..

  16. 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.

  17. 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

  18. 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.

  19. 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

  20. 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….

  21. 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?

  22. @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..:)

  23. 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

  24. 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..

  25. @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 ….

  26. @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…

  27. 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 ;

  28. 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….

  29. Avijit Paul says

    Hey lorenz ,A very Gr8 tutorial ….

    i was just trying to get the orginal image when the discard button is clicked while cropping the image …

    could anyone thrwow some idea how to do this ???

  30. priska says

    hi thank your for your amazing tutorial. but i have a question,
    how to change the image size dynamically like using a motion event when the screen touched?
    The example you provided, final result of the image is given to 200×200 but what I want is the user can resize the rectangular by touching the screen.

    Thank you in advance

    • dla says

      The code example will not work on all versions of Android, nor will it work on all vendor’s versions. This bit of code relies on code that is not part of the API. AFAIK the only way to do cropping is to put the code directly in your app.

  31. Flichex says

    I have a problem with this code in Android 2.3.7 and Android 4.0. Do you know what happen? Could you tell me how to resolve it?

      • Flichex says

        So, Is it not possible to make crop in all Android versions? Could you give me a suggestion about how to make a image crop for all android versions?

  32. Andrea says

    hi, i’ve got a problem.. if I take the photo from the gallery is crop normally, but if I take a picture the device told me that the gallery stops working… why?

  33. Vikram says

    Hi,

    How can I crop image in assets folder.I tried below code but it is some how not working

    Uri uri = Uri.parse(“file:///android_asset/images/icon.jpg);

    Please help me.
    Thanks,
    ~Vikram

  34. AKash says

    I want to use drawable image instead to get image from camera and sd card so how can i change it? please tell me solution

  35. Shridutt kothari says

    Choose from Gallery wont work on KItKat version, will give you error
    java.lang.SecurityException: Permission Denial: writing com.android.providers.media.Media Documents ……
    …….Provider uri requires android.permission.MANAGE DOCUMENTS, or grantUriPermission()

Leave a Reply

Your email address will not be published. Required fields are marked *