Tuesday, July 10, 2012

How to Crop Image from camera and gallery in Android


                
Hi Friends,
I am going to explore a sample application in android ,which gives you
an idea , How to select Image from gallery and how to capture image from camera and after it crop it according our use...
For this I have used android default camera and android default gallery...
Hope this will helps you......

1- Print Screen of Home Page



2-Android Manifest file

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="camera.test.demo"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk android:minSdkVersion="8" />

<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<activity
android:name=".SimpleCameraGalleryDemo"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

</manifest>

3-SimpleCameraGalleryDemo Code

package camera.test.demo;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

public class SimpleCameraGalleryDemo extends Activity {
private static final int PICK_FROM_CAMERA = 1;
private static final int PICK_FROM_GALLERY = 2;
ImageView imgview;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

imgview = (ImageView) findViewById(R.id.imageView1);
Button buttonCamera = (Button) findViewById(R.id.btn_take_camera);
Button buttonGallery = (Button) findViewById(R.id.btn_select_gallery);
buttonCamera.setOnClickListener(new View.OnClickListener() {

public void onClick(View v) {
// call android default camera
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

intent.putExtra(MediaStore.EXTRA_OUTPUT,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI.toString());
// ******** code for crop image
intent.putExtra("crop", "true");
intent.putExtra("aspectX", 0);
intent.putExtra("aspectY", 0);
intent.putExtra("outputX", 200);
intent.putExtra("outputY", 150);

try {

intent.putExtra("return-data", true);
startActivityForResult(intent, PICK_FROM_CAMERA);

} catch (ActivityNotFoundException e) {
// Do nothing for now
}
}
});
buttonGallery.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent();
// call android default gallery
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
// ******** code for crop image
intent.putExtra("crop", "true");
intent.putExtra("aspectX", 0);
intent.putExtra("aspectY", 0);
intent.putExtra("outputX", 200);
intent.putExtra("outputY", 150);

try {

intent.putExtra("return-data", true);
startActivityForResult(Intent.createChooser(intent,
"Complete action using"), PICK_FROM_GALLERY);

} catch (ActivityNotFoundException e) {
// Do nothing for now
}
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

if (requestCode == PICK_FROM_CAMERA) {
Bundle extras = data.getExtras();
if (extras != null) {
Bitmap photo = extras.getParcelable("data");
imgview.setImageBitmap(photo);

}
}

if (requestCode == PICK_FROM_GALLERY) {
Bundle extras2 = data.getExtras();
if (extras2 != null) {
Bitmap photo = extras2.getParcelable("data");
imgview.setImageBitmap(photo);

}
}
}
}

4-main.xml File

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<TextView
android:id="@+id/textViewAddCard"
android:layout_width="250dp"
android:layout_height="50dp"
android:text="Take Image"
android:textSize="16dp"
android:layout_gravity="center"
android:gravity="center"
android:typeface="sans"/>

<Button
android:id="@+id/btn_take_camera"
android:layout_width="250dp"
android:layout_height="50dp"
android:text="Take From Camera"
android:layout_marginTop="5dp"
android:layout_gravity="center"
android:typeface="sans"/>

<Button
android:id="@+id/btn_select_gallery"
android:layout_width="250dp"
android:layout_height="50dp"
android:text="Select from Gallery"
android:layout_marginTop="10dp"
android:layout_gravity="center"
android:typeface="sans" />
<ImageView
android:id="@+id/imageView1"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>



Just copy above code and save your life...

132 comments:

  1. Hi, thank you for your codes! I was wondering how do i edit the codes because i dont need the crop picture function. Can i get your help on this?

    ReplyDelete
    Replies
    1. yes sure!
      just remove crop image code from your activity-
      intent.putExtra("crop", "true");
      intent.putExtra("aspectX", 0);
      intent.putExtra("aspectY", 0);
      intent.putExtra("outputX", 200);
      intent.putExtra("outputY", 150);

      Thanks,

      Delete
    2. Hi, thank you alot for your help. I am a student working on a Android Programming Project. I am new on this. Do you mind helping me out with some of my doubts? If you dont mind, do you have an email so I could contact you with? Let me know if you are uncomfortable with it. Thank you.

      Delete
    3. Hi, No issue you can make me a detail mail my id is-manishsri01@gmail.com

      Thanks,

      Delete
  2. can we use explicit intent for cropping image

    ReplyDelete
    Replies
    1. Hello,
      I am not sure but it should work. If you did not get anything in bundle or in data is null you should get image path after capture an image and then try to crop it..
      Like this-
      public void callCamera() {
      Intent cameraIntent = new Intent(
      android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
      startActivityForResult(cameraIntent, CAMERA_REQUEST);
      }

      and after that-
      protected void onActivityResult(int requestCode, int resultCode, Intent data) {
      if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
      Bitmap photo = (Bitmap) data.getExtras().get("data");

      /**
      * Get Path
      */
      Uri selectedImage = data.getData();
      String[] filePathColumn = { MediaStore.Images.Media.DATA };

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

      columnIndex = cursor.getColumnIndex(filePathColumn[0]);

      /**
      *
      */

      and after that crop it...

      Delete
    2. after that how to crop it? i have defined a button named crop in java class itself and i want when the user click on crop then the image should be crop but don't know how to do it,,,because when you make a button in java class you don't have any id of in in R.java file

      Delete
  3. Replies
    1. Your welcome, and thanks for positive comment on my post..

      Delete
  4. hi here in your code i want to change these two lines
    intent.putExtra("outputX", 200);
    intent.putExtra("outputY", 150); to


    intent.putExtra("outputX", 600);
    intent.putExtra("outputY", 500);

    but it is not working.I want to change size of output image.

    ReplyDelete
    Replies
    1. Hi,
      intent.putExtra("outputX", 200);
      intent.putExtra("outputY", 150)

      these line not for image size it is just for crop image size in 2:1.5 ratio..
      you can increase it using your fingers. My advice is don't fix it to-
      intent.putExtra("outputX", 600);
      intent.putExtra("outputY", 500);
      because everyone don't have high resolution screen device..

      Delete
  5. if i increase with my fingers for example if i take completes image the output image doesn't contain whole complete image it is cropping automatically and i am not able to see whole image.And in cropping screen,there are two buttons save and cancel.If i want to change text on them how can i change.please help me.

    ReplyDelete
    Replies
    1. For your first problem for crop image I am not sure what have to do because in my case its working fine. Actually it is totally depend upon your device density. For this I suggest you ask question on stackoverflow.com and if you got any answer please put your answer on my blog so I and my other visitor can take help from you.

      And second question for change save and cancel button. so when we use-intent.putExtra("crop", "true");
      this is android default behavior we have no any control or we should override OS.
      well it will be different text and button on different-different devices.

      Thank you so much and I am waiting for your comment.

      Delete
  6. is it possible to keep pinch zoom in and zoom out for those images which i have selected from gallery so that i can make zoom in on image and fix in that box and so that i can get full image

    ReplyDelete
    Replies
    1. No I don't think it is possible zoom in after crop image. Better idea don't crop. Just remove crop code hope it will help you. Or search for any android library for crop image in full.

      Delete
    2. thanks i will search if i get solution i will put answer in your blog

      Delete
    3. i want to know that how that rectangle is coming and how to get size of rectangle.

      Delete
    4. This is depend upon android device density and size-
      Basically this is Android SDk default behavior we are not going to create any rectangle from our self..
      for testing just remove below 2 line from your crop code-
      intent.putExtra("aspectX", 0);
      intent.putExtra("aspectY", 0);

      you will see still its working but rectangle ratio is change now-
      and yes you can create your own Canvas for crop image in a fix size in any shape some thing like this-

      Bitmap targetBitmap = Bitmap.createBitmap(targetWidth, targetHeight,
      Bitmap.Config.ARGB_8888);
      Canvas canvas = new Canvas(targetBitmap);
      Path path = new Path();
      path.addCircle(((float) targetWidth) / 2,
      ((float) targetHeight) / 2,
      (Math.min(((float) targetWidth), ((float) targetHeight)) / 2),
      Path.Direction.CW);
      Paint paint = new Paint();
      paint.setColor(Color.GRAY);
      //paint.setStyle(Paint.Style.STROKE);
      paint.setStyle(Paint.Style.FILL);
      paint.setAntiAlias(true);
      paint.setDither(true);
      paint.setFilterBitmap(true);
      canvas.drawOval(new RectF(0, 0, targetWidth, targetHeight), paint) ;
      //paint.setColor(Color.TRANSPARENT);
      canvas.clipPath(path);
      Bitmap sourceBitmap = scaleBitmapImage;
      canvas.drawBitmap(sourceBitmap, new Rect(0, 0, sourceBitmap.getWidth(),
      sourceBitmap.getHeight()), new RectF(0, 0, targetWidth,
      targetHeight), paint);

      Delete
  7. This comment has been removed by the author.

    ReplyDelete
  8. Hi, do you know the reason why i run your app in my android phone (Samsung Galaxy Nexus), it pop up a message saying "unfortunately, your app has stopped running."

    ReplyDelete
    Replies
    1. Hi Jaden can you paste your error log here?
      Well this camera code have issue with samsung gallexy series mobiles.
      Actually because of good quality high resolution image data got null in OnActivity Result..
      So try to get url of image instead of data..try below code-

      /**
      * On activity result
      */

      protected void onActivityResult(int requestCode, int resultCode, Intent data) {
      /**
      * Get Path
      */
      Uri selectedImage = data.getData();
      String[] filePathColumn = { MediaStore.Images.Media.DATA };

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

      if (((requestCode == CAMERA_REQUEST)||(requestCode == PICK_FROM_GALLERY)) && resultCode == RESULT_OK) {
      //Bitmap photo = (Bitmap) data.getExtras().get("data");

      columnIndex = cursor.getColumnIndex(filePathColumn[0]);
      picturePath = cursor.getString(columnIndex);
      Log.e("Image View Path1", picturePath);
      Log.e("Selected Image path camera", String.valueOf(columnIndex));
      Bitmap yourSelectedImage = BitmapFactory.decodeFile(picturePath);
      // convert bitmap to byte
      ByteArrayOutputStream stream = new ByteArrayOutputStream();
      yourSelectedImage.compress(Bitmap.CompressFormat.PNG,100, stream);
      byte imageInByte[] = stream.toByteArray();
      // Inserting Contacts
      Log.d("Insert: ", "Inserting ..");
      db.addContact(new Contact("Android", imageInByte));
      Intent intent = new Intent(SQLiteDemoActivity.this,SQLiteDemoActivity.class);
      startActivity(intent);
      finish();
      }
      cursor.close();

      }

      Delete
  9. 04-26 11:38:06.107: E/Trace(1834): error opening trace file: No such file or directory (2)
    04-26 11:38:06.162: D/AndroidRuntime(1834): Shutting down VM
    04-26 11:38:06.162: W/dalvikvm(1834): threadid=1: thread exiting with uncaught exception (group=0x40c08600)
    04-26 11:38:06.170: E/AndroidRuntime(1834): FATAL EXCEPTION: main
    04-26 11:38:06.170: E/AndroidRuntime(1834): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{camera.test.demo/camera.test.demo.SimpleCameraGalleryDemo}: java.lang.ClassNotFoundException: Didn't find class "camera.test.demo.SimpleCameraGalleryDemo" on path: /data/app/camera.test.demo-1.apk
    04-26 11:38:06.170: E/AndroidRuntime(1834): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2222)
    04-26 11:38:06.170: E/AndroidRuntime(1834): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2356)
    04-26 11:38:06.170: E/AndroidRuntime(1834): at android.app.ActivityThread.access$600(ActivityThread.java:150)
    04-26 11:38:06.170: E/AndroidRuntime(1834): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1244)
    04-26 11:38:06.170: E/AndroidRuntime(1834): at android.os.Handler.dispatchMessage(Handler.java:99)
    04-26 11:38:06.170: E/AndroidRuntime(1834): at android.os.Looper.loop(Looper.java:137)
    04-26 11:38:06.170: E/AndroidRuntime(1834): at android.app.ActivityThread.main(ActivityThread.java:5193)
    04-26 11:38:06.170: E/AndroidRuntime(1834): at java.lang.reflect.Method.invokeNative(Native Method)
    04-26 11:38:06.170: E/AndroidRuntime(1834): at java.lang.reflect.Method.invoke(Method.java:511)
    04-26 11:38:06.170: E/AndroidRuntime(1834): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:795)
    04-26 11:38:06.170: E/AndroidRuntime(1834): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:562)
    04-26 11:38:06.170: E/AndroidRuntime(1834): at dalvik.system.NativeStart.main(Native Method)
    04-26 11:38:06.170: E/AndroidRuntime(1834): Caused by: java.lang.ClassNotFoundException: Didn't find class "camera.test.demo.SimpleCameraGalleryDemo" on path: /data/app/camera.test.demo-1.apk
    04-26 11:38:06.170: E/AndroidRuntime(1834): at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:65)
    04-26 11:38:06.170: E/AndroidRuntime(1834): at java.lang.ClassLoader.loadClass(ClassLoader.java:501)
    04-26 11:38:06.170: E/AndroidRuntime(1834): at java.lang.ClassLoader.loadClass(ClassLoader.java:461)
    04-26 11:38:06.170: E/AndroidRuntime(1834): at android.app.Instrumentation.newActivity(Instrumentation.java:1054)
    04-26 11:38:06.170: E/AndroidRuntime(1834): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2213)
    04-26 11:38:06.170: E/AndroidRuntime(1834): ... 11 more
    04-26 11:38:08.154: I/Process(1834): Sending signal. PID: 1834 SIG: 9

    ReplyDelete
  10. and this as well ...


    04-26 11:39:43.295: E/Trace(1969): error opening trace file: No such file or directory (2)
    04-26 11:39:43.318: D/AndroidRuntime(1969): Shutting down VM
    04-26 11:39:43.318: W/dalvikvm(1969): threadid=1: thread exiting with uncaught exception (group=0x40c08600)
    04-26 11:39:43.318: E/AndroidRuntime(1969): FATAL EXCEPTION: main
    04-26 11:39:43.318: E/AndroidRuntime(1969): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{camera.test.demo/camera.test.demo.SimpleCameraGalleryDemo}: java.lang.ClassNotFoundException: Didn't find class "camera.test.demo.SimpleCameraGalleryDemo" on path: /data/app/camera.test.demo-1.apk
    04-26 11:39:43.318: E/AndroidRuntime(1969): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2222)
    04-26 11:39:43.318: E/AndroidRuntime(1969): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2356)
    04-26 11:39:43.318: E/AndroidRuntime(1969): at android.app.ActivityThread.access$600(ActivityThread.java:150)
    04-26 11:39:43.318: E/AndroidRuntime(1969): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1244)
    04-26 11:39:43.318: E/AndroidRuntime(1969): at android.os.Handler.dispatchMessage(Handler.java:99)
    04-26 11:39:43.318: E/AndroidRuntime(1969): at android.os.Looper.loop(Looper.java:137)
    04-26 11:39:43.318: E/AndroidRuntime(1969): at android.app.ActivityThread.main(ActivityThread.java:5193)
    04-26 11:39:43.318: E/AndroidRuntime(1969): at java.lang.reflect.Method.invokeNative(Native Method)
    04-26 11:39:43.318: E/AndroidRuntime(1969): at java.lang.reflect.Method.invoke(Method.java:511)
    04-26 11:39:43.318: E/AndroidRuntime(1969): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:795)
    04-26 11:39:43.318: E/AndroidRuntime(1969): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:562)
    04-26 11:39:43.318: E/AndroidRuntime(1969): at dalvik.system.NativeStart.main(Native Method)
    04-26 11:39:43.318: E/AndroidRuntime(1969): Caused by: java.lang.ClassNotFoundException: Didn't find class "camera.test.demo.SimpleCameraGalleryDemo" on path: /data/app/camera.test.demo-1.apk
    04-26 11:39:43.318: E/AndroidRuntime(1969): at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:65)
    04-26 11:39:43.318: E/AndroidRuntime(1969): at java.lang.ClassLoader.loadClass(ClassLoader.java:501)
    04-26 11:39:43.318: E/AndroidRuntime(1969): at java.lang.ClassLoader.loadClass(ClassLoader.java:461)
    04-26 11:39:43.318: E/AndroidRuntime(1969): at android.app.Instrumentation.newActivity(Instrumentation.java:1054)
    04-26 11:39:43.318: E/AndroidRuntime(1969): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2213)
    04-26 11:39:43.318: E/AndroidRuntime(1969): ... 11 more
    04-26 11:39:48.279: I/Process(1969): Sending signal. PID: 1969 SIG: 9

    ReplyDelete
    Replies
    1. As you can see-
      Caused by: java.lang.ClassNotFoundException: Didn't find class "camera.test.demo.SimpleCameraGalleryDemo" on path: /data/app/camera.test.demo-1.apk

      that mean something wrong with your code, have you declare SimpleCameraGalleryDemo in your manifest?
      or package name or file name is change..
      Please copy whole project with same class name and package name..

      and one more thing let me know your app crash on open camera or on launch your app?

      Delete
  11. Ok. i will try it out. It crashes when i launch the app.

    ReplyDelete
  12. Hi, I am able to crop now but its only select from gallery. However, when i use camera and take a picture and try to crop it, the app crashes.

    ReplyDelete
    Replies
    1. what was the issue?
      well for camera crash you can try above code what I was comment -
      String[] filePathColumn = { MediaStore.Images.Media.DATA };

      Cursor cursor = getContentResolver().query(selectedImage,filePathColumn, null, null, null);
      cursor.moveToFirst()
      ..
      Hope it will help you..

      Delete
  13. It is the package name - SimpleCameraGalleryDemo - name conflicted. I solved it as you said and manage to select from image gallery and crop it.

    However, when i select camera, it crashes.

    And for the above code you gave it to me.... where do i place it in my coding?

    ReplyDelete
    Replies
    1. Okay so you can check this comment-
      http://www.androidhub4you.com/2012/07/how-to-crop-image-from-camera-and.html?showComment=1366951009757#c5794834984697151711

      logic is that- Samsung Gallexy serise mobile have good quality of camera so their size is also big that's why we got data==null in OnactivityResult.
      for avoiding this issue get last image capture location in your memory card and convert it into bitmap.

      Delete
  14. Do i add the above given comment code into the OnActivityResult method for camera??

    ReplyDelete
  15. and replace with the old ones that were given in the post?

    P.S:
    I apologized, i am just confused about the coding for the camera.

    ReplyDelete
    Replies
    1. just change whole onActivityResult with new one..

      Delete
    2. Hi see below code in my case I am using on button and dialog box for camera and gallery instead of two button-
      public class SQLiteDemoActivity extends Activity {
      Button addImage;
      private static final int CAMERA_REQUEST = 1;
      private static final int PICK_FROM_GALLERY = 2;
      int columnIndex;
      String picturePath="path";
      ListView dataList;
      int imageId;
      Bitmap theImage;
      /** Called when the activity is first created. */
      @Override
      public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.main);
      /**
      * open dialog for choose camera/gallery
      */

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

      builder.setTitle("Select Option");
      builder.setAdapter(adapter, new DialogInterface.OnClickListener() {

      public void onClick(DialogInterface dialog, int which) {
      // TODO Auto-generated method stub
      Log.e("Selected Item", String.valueOf(which));
      if (which == 0) {
      callCamera();
      }
      if (which == 1) {
      callGallery();
      }

      }
      });
      final AlertDialog dialog = builder.create();

      addImage = (Button) findViewById(R.id.btnAdd);

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

      }

      /**
      * On activity result
      */

      protected void onActivityResult(int requestCode, int resultCode, Intent data) {
      /**
      * Get Path
      */
      Uri selectedImage = data.getData();
      String[] filePathColumn = { MediaStore.Images.Media.DATA };

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

      if (((requestCode == CAMERA_REQUEST)||(requestCode == PICK_FROM_GALLERY)) && resultCode == RESULT_OK) {
      //Bitmap photo = (Bitmap) data.getExtras().get("data");

      columnIndex = cursor.getColumnIndex(filePathColumn[0]);
      picturePath = cursor.getString(columnIndex);
      Log.e("Image View Path1", picturePath);
      Log.e("Selected Image path camera", String.valueOf(columnIndex));
      Bitmap yourSelectedImage = BitmapFactory.decodeFile(picturePath);//this is your result

      }
      cursor.close();

      }

      /**
      * open camera method
      */
      public void callCamera() {
      Intent cameraIntent = new Intent(
      android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
      startActivityForResult(cameraIntent, CAMERA_REQUEST);
      }

      /**
      * open gallery method
      */

      public void callGallery() {
      Intent intent = new Intent();
      intent.setType("image/*");
      intent.setAction(Intent.ACTION_GET_CONTENT);
      intent.putExtra("return-data", true);
      startActivityForResult(Intent.createChooser(intent, "Complete action using"),PICK_FROM_GALLERY);

      }

      }

      Delete
  16. Can you please tell me how to remove the spacing from image, that is when I capture image onResult the image is set but there is spacing in background, so how could I remove it?

    ReplyDelete
    Replies
    1. This spacing because of cropping image I mean suppose you capture an Image size of 480*720 and after that you crop it just half 240*360 that's why you are getting black dark shade in background.
      For this you should check device resolution and crop image according it..
      Well if you got any better solution please let me know and please publish you comment on my blog so other user can get help from you..

      Thanks..

      Delete
  17. hi may i know what is the problem that occurred, when i run your app, everything is fine. Until, after the crop section. The cropped image does not show up at all.

    ReplyDelete
  18. Hi yan!
    Let me know please which device you are using for testing may be it happens because of high resolution image.
    May be your device memory size is less so you did not got any thing..
    and please cross check for camera and gallery in both case you are getting same issue?

    ReplyDelete
  19. hi manish, i am using a galaxy nexus.
    so i guess it is the resolution? but i previous run this codes on my phone but it was fine. but the next day my codes fail to run. My memory size is about 1gb left so i doubt that is the problem

    ReplyDelete
    Replies
    1. yes may be remove some app from your phone and try again..and yes you are right problem is the high resolution image.

      Delete
    2. hmm... tried so but still not able to run the program still

      Delete
    3. Please try to debug code using debugger I think you got null data that's why not able to get image after crop..
      Use debugger please..
      and one more testing remove crop code from your project then try again..
      Remove these lines from your code-

      intent.putExtra("crop", "true");
      intent.putExtra("aspectX", 0);
      intent.putExtra("aspectY", 0);
      intent.putExtra("outputX", 200);
      intent.putExtra("outputY", 150);

      Delete
    4. hi manish, sorry for this. but i am a beginner programmer for android apps. erm.. i did remove the cropping code but it still does not work. now i try checking for null data but it says imagebyte is not used.

      Delete
  20. hi
    In my code i want to use gallery but one problem is that get images from drawable and crop it and set as wallpaper so can you please help me??

    Thanks in advance

    ReplyDelete
    Replies
    1. I think you can't open a crop window for drawable image for that you should use canvas. you can Goggling for that and you can check my below comment it will give you a little idea about it-

      http://www.androidhub4you.com/2012/07/how-to-crop-image-from-camera-and.html?showComment=1366178156846#c3655311558111274569

      Delete
    2. I got code but when store in sd card image will going to distorting.

      Delete
  21. I have one code but in that when i crop image and store it into sd card then it will be blurry so not able to set as wallpaper.

    ReplyDelete
    Replies
    1. yes dear after crop image it will got blurry in this case I can't help I think don't crop more or try perfect ratio to crop image..

      Delete
  22. when i click on camera then camera open and take pick and when click on save my apps crashed and showing msg

    java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=0, data=null} to activity {com.example.cropaftercapture/com.example.cropaftercapture.MainActivity}: java.lang.NullPointerException


    plz help me and thanks in advance PLZ

    ReplyDelete
    Replies
    1. As you can see your data is null that's why your application got crash..
      I think you are using Samsung phone for testing. In High Density device image size is big so we got data==null.
      for that just capture image and get last path of image and crop it..

      Just follow my this comment or do googling -
      http://www.androidhub4you.com/2012/07/how-to-crop-image-from-camera-and.html?showComment=1361894006692#c1709361995420601649

      Thanks,

      Delete
  23. protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == PICK_FROM_GALLERY
    && resultCode == Activity.RESULT_OK) {
    // code here
    }
    }

    Without "resultCode == Activity.RESULT_OK" this checking, the app forces close on back button press

    ReplyDelete
    Replies
    1. Hi it is becasuse of null data on press back button so please change your code-
      protected void onActivityResult(int requestCode, int resultCode, Intent data) {
      if(data!=null){
      if (requestCode == PICK_FROM_CAMERA) {
      Bundle extras = data.getExtras();
      if (extras != null) {
      Bitmap photo = extras.getParcelable("data");
      imgview.setImageBitmap(photo);
      }
      }

      Enjoy..

      Delete
  24. i have a problem, how can i save the image that has been crop into my phone gallery?

    ReplyDelete
  25. thank you very much,
    I have a problem ...
    on galaxy s with android 2.3.3,
    after taking the picture and highlight the crop area the image saved without getting back to the app activity, it get back to the camera android the onActivityResult() will not be invoked
    how to solve this ?

    ReplyDelete
    Replies
    1. I've tried the code on sony xperia s with android 4.0 it works without error.

      Delete
    2. Yes Firas you are right I have also same issue its work on some devices and failed on some..
      Error is who==null;

      I think it is because of high resolution image..
      Please try it on google..

      Delete
    3. Ok thank you for the fast response,
      I don't think the problem because if high resolution cause the xperia s is 12mp
      and the galaxy s is 5mp.
      I will try on google thanx :-)

      Delete
    4. I tested it on HTC 4.0 and Samsung Gallexy S Dues and its working fine..
      Please check on google and if got answer please paste here so other people got help from you..
      Thanks,

      Delete
  26. Thanks for your code.. but how can get exact path of cropped image. I want upload it to the server

    ReplyDelete
    Replies
    1. Hi I got same question on stackoverflow-
      search it on google- "stack overflow question number 14534625"

      Thanks,

      Delete
  27. hi, can you tell me, how to pass the cropped image from one activity to another activity?
    it showing classcastexception...

    ReplyDelete
    Replies
    1. Hi, where I add bitmap into imageview from there call an intent for next page and put your image something like that-
      Intent intnt = new Intent(A.this,Bclass);
      intnt.putExtra("photo", photo);
      startActivity(intnt);

      And on activity B-
      Intent intnt = getIntent();
      final Bitmap crop_photo = (Bitmap) intnt.getParcelableExtra("photo");

      Thanks,

      Delete
  28. thank u so much.. it's working. i did a small mistake. thanks a lot..

    ReplyDelete
  29. Hey manish, I am done with the path of cropped image.... Now i want cal aspx page from android... do you know how to do this.....

    ReplyDelete
    Replies
    1. use web services follow my below post-
      http://www.androidhub4you.com/2012/09/consuming-rest-web-services-in-android.html

      Delete
  30. hello manish..thanks for sharing a nice tutorial on image cropping in android..im new to android can you help me in my projects...some guidance im stuck up in some parts..
    :(

    ReplyDelete
  31. Hi Manish,
    How do we crop an image if we have it's path ?
    In one of your replies (http://www.androidhub4you.com/2012/07/how-to-crop-image-from-camera-and.html?showComment=1361894006692#c1709361995420601649) you explained how to get the captured image path, could you please explain how to let the user crop it ?
    Thanks in advance

    ReplyDelete
    Replies
    1. Hi this is normally not happen so you can use canvas for it.
      See one of my comment on this post-
      http://www.androidhub4you.com/2012/07/how-to-crop-image-from-camera-and.html?showComment=1366178156846#c3655311558111274569

      Delete
  32. After cropping image i want to upload to server and get link of that uploaded image. But when crop and press save it just give crop image. How could i upload it?

    ReplyDelete
    Replies
    1. Hi after cropping don't set your image in any imageview, just call web services for upload your image on server..

      Delete
  33. I ran this code in samsung galaxy y dual(api level 8) I got the output, but when i run it in Celkon(android 4.0) i'm getting error message. Unfortunatuly Gallery is closed.So i removed Intent.putExtra("crop", "true")line then It works fine .Why? can you explain please

    ReplyDelete
  34. Do you know how to get the coordinates(X,Y,H,W) of the cropped image?

    ReplyDelete
    Replies
    1. In my knowledge we can't get coordinate of crop image but we can set coordinate.
      intent.putExtra("crop", "true");
      intent.putExtra("aspectX", 0);
      intent.putExtra("aspectY", 0);
      intent.putExtra("outputX", 200);
      intent.putExtra("outputY", 150);

      Read more: http://www.androidhub4you.com/2012/07/how-to-crop-image-from-camera-and.html#ixzz2eec2wNjP

      Delete
  35. Hi Manish,
    This is really a great tutorial, I have searched over a lot of websites and finally landed up here.
    My requirement is to take a picture and crop it and show it on the ImageView.

    With your code, I am able to take the picture, but upon confirming the picture, the app is crashing.

    When i commented out the cropping part, its working fine

    i.e. intent.putExtra("crop", "true");
    intent.putExtra("aspectX", 0);
    intent.putExtra("aspectY", 0);
    intent.putExtra("outputX", 200);
    intent.putExtra("outputY", 150);

    But, The cropping and displaying of image from gallery works fine, though my requirement is to capture and crop the image.

    Can you please guide me where i went wrong or what is problem?

    ReplyDelete
    Replies
    1. Hi Satish,
      Thanks for comming here and share your problem with me. Actually you are not doing anything wrong. problem with android OS. In market many size and many company devices and they have their own camera resolution and their own way to override android OS.
      I also got stuck same code working fine on HTC device and some of Samsung device but some of Samsung device have issue.

      I am using Samsung gallexy s-dues, HTC Desire and its working fine camera and gallery both but one of my friend have samsung device and I am getting crash on Gallery and on one of my user having crash on Camera.I am really got stuck. I don't know why Android allow to override OS like that.

      Actually problem is data when you are call camera or gallery Intent and getting in onActivityResult() data came null, that's why application got crash.

      for that I try many thing like getting direct path and after that crop that image but now this code is working fine on high density device but got crash on lower density devices :)

      Well If you don't want crop Image you can get it using it's path and display in Imageview. Please discuss your views, sure I will help you.

      Thanks,

      Delete
  36. Hi Manish,
    This code looks awesome,do you know how to give overlay points on the image so that image can be cropped as per the points boundary...something like camscanner android application.Do help me with your answer.

    ReplyDelete
    Replies
    1. Hi Robin,
      I think you should use canvas. It will help you to crop image in custom ratio like-circle,square etc.

      Delete
    2. can you help me,if you have any code

      Delete
    3. Sorry dear I don't have any code. Just see this comment hope it will help you-
      http://www.androidhub4you.com/2012/07/how-to-crop-image-from-camera-and.html?showComment=1366178156846#c3655311558111274569

      Delete
  37. This comment has been removed by the author.

    ReplyDelete
  38. Hi Manish..i would like to say thanks first for ur post..its helping to me ..but when i m taking image from Camera i am unble to crop it app is crashing ..cuold u please help me..

    my code is:

    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

    intent.putExtra(MediaStore.EXTRA_OUTPUT,
    MediaStore.Images.Media.EXTERNAL_CONTENT_URI.toString());
    // ******** code for crop image
    intent.putExtra("crop", "true");
    intent.putExtra("aspectX", 0);
    intent.putExtra("aspectY", 0);
    intent.putExtra("outputX", 200);
    intent.putExtra("outputY", 150);

    try {

    intent.putExtra("return-data", true);
    startActivityForResult(intent, PICK_FROM_CAMERA);

    } catch (ActivityNotFoundException e) {
    // Do nothing for now
    }



    onActivityResults:

    if(requestCode == PICK_FROM_CAMERA)
    {
    Bundle extras = data.getExtras();

    if (extras != null) {
    Bitmap photo = extras.getParcelable("data");
    ImageView picView = (ImageView)findViewById(R.id.picture);
    //display the returned cropped image
    picView.setImageBitmap(photo);
    }
    //imgview.setImageBitmap(photo);


    }//user is returning from cropping the image

    ReplyDelete
  39. hi, how can i get the best result of cropping image, so that the resolution of cropped image same as original ( quality)..
    thanks

    ReplyDelete
    Replies
    1. Suppose you have imageView of size 200x200 or you want send that image 150x150 size on server so crop that image in that ratio else it will be blur.

      Delete
  40. could you please send me the zip
    getanoopwayanad@gmail.com

    ReplyDelete
    Replies
    1. Sorry Anoop don't have code. Just copy from above it is very simple code...

      Thanks!

      Delete
  41. This comment has been removed by the author.

    ReplyDelete
  42. ok...i have done this....thank u so much. there is small problem everything work fine but when we press the back button(after the cropping option) on the mobile, appilcation crashes. after cropping when we press save or cancel it is fine..
    i think you got my problem......could you please help.

    ReplyDelete
  43. Yes yes just check for null data -
    if (requestCode == PICK_FROM_CAMERA) {
    if(data!= null) {
    Bundle extras = data.getExtras();
    if (extras != null) {
    Bitmap photo = extras.getParcelable("data");
    imgview.setImageBitmap(photo);

    }
    }

    i am not sure but i think it should work please check and update me..

    Thanks!

    ReplyDelete
  44. I want to crop an image in my application when it is selected from gallery.My cropping code work from the simulator but not properly work on phones. I set outputX=400 and outputY =487. In my simulator i get the output bitmap with 400 x 487 resolution,but when i cropped the image from gallery i get the output bitmap with 145 x 177 resolution. Why does it happen?

    ReplyDelete
    Replies
    1. it is because of device density. It will be different-different on different devices.

      Delete
  45. My system "photo crop" app working for crop but "Picture Crop" app is not responding when i click on save button...
    Do u have any solution for it
    @Override
    public void onClick(View v) {
    // TODO Auto-generated method stub
    switch(v.getId()){
    case R.id.buttonCam:
    try{
    Intent it=new Intent(getApplicationContext(),MyCustomCamera.class);
    startActivityForResult(it, PICK_FROM_CAMERA);
    }catch(Exception e){
    e.printStackTrace();
    }

    break;
    case R.id.buttonGall:
    try{
    Intent intnt = new Intent();
    intnt.setType("image/*");
    intnt.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(Intent.createChooser(intnt, "Complete action using"), PHOTO_PICKED);
    }catch(Exception e){e.printStackTrace();}
    break;
    }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // TODO Auto-generated method stub
    super.onActivityResult(requestCode, resultCode, data);

    switch(requestCode){
    case 1:
    if(resultCode==RESULT_OK){
    String mydir = data.getExtras().getString("image_path");
    File f1=new File(mydir);
    cropCaptureImage(Uri.fromFile(f1));
    }
    break;
    case 2:
    if(resultCode==RESULT_OK){

    cropCaptureImage(data.getData());
    }
    break;
    case 3:
    if(resultCode==RESULT_OK){
    Bundle extras = data.getExtras();

    Bitmap thePic = (Bitmap)extras.get("data");
    ByteArrayOutputStream baos= new ByteArrayOutputStream();
    thePic.compress(CompressFormat.JPEG, 100, baos);
    byte[] byteArr=baos.toByteArray();
    Intent it=new Intent(MainWindow.this,MainActivity.class);
    it.putExtra("myImage",byteArr);
    startActivity(it);
    }else{
    return;
    }

    break;
    }
    }

    private void cropCaptureImage(Uri picUri) {
    // TODO Auto-generated method stub
    try{
    Intent cropIntent=new Intent("com.android.camera.action.CROP");
    List list = getPackageManager().queryIntentActivities( cropIntent, 0 );
    int size = list.size();
    if (size == 0) {
    Toast.makeText(this, "Can not find image crop app", Toast.LENGTH_SHORT).show();
    return;
    } else {
    cropIntent.setDataAndType(picUri, "image/*");
    cropIntent.putExtra("crop", "true");
    cropIntent.putExtra("aspectX", 1);
    cropIntent.putExtra("aspectY", 1);
    cropIntent.putExtra("outputX", sv.getWidth());
    cropIntent.putExtra("outputY", sv.getHeight());
    cropIntent.putExtra("scale", true);
    cropIntent.putExtra("return-data", true);

    startActivityForResult(cropIntent, 3);
    }
    }catch(Exception e){e.printStackTrace();}



    ReplyDelete
  46. Hii M.S, I have problem with cropping a large image, its didn't work for more than 600 px image resolution

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

    if(requestCode == FILE){
    UrlGambar = data.getData();
    performCrop();

    }

    else if(requestCode == PIC_CROP){
    Bundle extras = data.getExtras();
    thePic = extras.getParcelable("data");
    ImageView picView = (ImageView)findViewById(R.id.tampil);
    picView.setImageBitmap(thePic);

    TextView text = (TextView) findViewById(R.id.height);
    TextView text2 = (TextView) findViewById(R.id.focal);
    TextView text3 = (TextView) findViewById(R.id.sh);
    Bitmap bMap = thePic;

    text.setText(Integer.toString(bMap.getHeight()));
    text2.setText(Float.toString(FocalLength));
    }
    }
    }

    how can I get picture Height and Focal length after cropping?


    private void performCrop(){
    try {

    Intent cropIntent = new Intent("com.android.camera.action.CROP");
    cropIntent.setDataAndType(UrlGambar, "image/*");
    cropIntent.putExtra("crop", "true");
    cropIntent.putExtra("aspectX", 0);
    cropIntent.putExtra("aspectY", 0);
    cropIntent.putExtra("scale", true);
    // cropIntent.putExtra("outputX",1500);
    //cropIntent.putExtra("outputY", 1500);
    cropIntent.putExtra("return-data", true);
    startActivityForResult(cropIntent, PIC_CROP);
    }
    catch(ActivityNotFoundException anfe){
    //display an error message
    String errorMessage = "Oops..Perangkat Anda tidak mendukung fungsi CROP!";
    Toast toast = Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT);
    toast.show();
    return;
    }
    }}

    ReplyDelete
  47. This comment has been removed by the author.

    ReplyDelete
  48. Hi Manish,

    Thanx for helping so many with ur code.Ur code worked fine for me.One prob is zoomin/zoomout is not working when resizing the crop frame in gallery picture but the same is working fine when clicking picture from camera upon resizing ZIN/ZOUT option working..Plz help me what can be done..Thanx in advance.

    Read more: http://www.androidhub4you.com/2012/07/how-to-crop-image-from-camera-and.html#ixzz36IMdtVj3

    ReplyDelete
    Replies
    1. So Simple just setonclicklistner on that imageview and on click open the camera and onActivityResult set image into imagview.

      Delete
  49. Thanx for the reply. I dont get you.. ur answer is not relevant for my question.If u run ur code..u l get to know while cropping image is zoomin/zoomout when u click picture..but when u select picture from gallery ZIN/ZOUT not happening while cropping.

    ReplyDelete
    Replies
    1. We have same croping code for both. So it should function same as well camera and gallery both.

      Delete
  50. Its not working the same way when i exactly copied ur code.U can also try and see.

    ReplyDelete
  51. its possible to get the multiple crop option an above code...pls share

    ReplyDelete
  52. Hi Manish,
    I have got problem for crop image. In Samsung galaxy tab , the selected URI give as null pointer exception,Please give me suggestion.

    ReplyDelete
  53. Hi Manish

    The crop is not working while selecting image from Gallery. After i select the image it does not give me option to crop. Please help me. Thanks

    ReplyDelete
  54. Thanks a ton brother ! I don't have words to express my gratitude towards you ! Just thanks a ton again !

    ReplyDelete
  55. Bro. I have just a small query ! if i set an image to this image view created as per your algorithm.. How am I suppose to save it and retrieve it during the app start and app close ?? Could you please help me on this ... eagerly waiting for your answer..

    ReplyDelete
    Replies
    1. you need to shave your image into sdcard or sqlite, try below link-

      http://www.androidhub4you.com/2012/09/hello-friends-today-i-am-going-to-share.html

      Delete
  56. Hi Srivastava,
    I have used your code.its working fantastic but In my application i need to upload the image with 100*100 size. How can i crop to this size.

    thanks & regaurds...

    ReplyDelete
    Replies
    1. Try something this-
      Bitmap finalImage = Bitmap.createScaledBitmap(srcImage, desiredHeight, desiredWidth, true);

      and use finalImage for sending image over the server. I am not sure but it should work for you.

      Delete
  57. hiiii manish your code run my samsung galaxy grand but when i run it on other devices like micromax and huwai it crashes while taking images and on save on it.

    ReplyDelete
  58. i can't find the croping function when i run it

    ReplyDelete
  59. Hi Manish,

    After capturing image from camera I want to set the same on imageView of resolution 300x246. I have used you code it is working for me but I am not able to use the same as per my requirement. Can you please provide the solution for the same.

    ReplyDelete
  60. Hi Manish,

    Thanks for this brilliant post!! It has really helped me.

    I've a query which might be out of the context of this development, but I would really appreciate if you could help me with that.

    I want to change the value / text in the buttons of 'Save', 'Cancel' and 'Crop' after a picture is taken from any Android device (samsung especially) and the result outcome as well.

    What happens in my app is, when you take a pic, you get the options to Save and Discard (I want to change the Save to Next). Once you Save it, you land on the Crop screen where you crop the intended image and press Crop. After the image is cropped, you again get the options to Crop or Cancel. At this stage, I want the options to be Done rather than the Crop and Cancel. Once Done is pressed, the cropped image is taken to my app screen.

    I tried looking for this in the Camera API, but couldn't get anything from there.

    Hope you could help me with this. Awaiting on your expert advice. Thanks!!

    ReplyDelete
    Replies
    1. Hi, this is android manufacture default feature, you can't override it. you need to implement your own surfaceview for custom requirement. you can try any cropping library too.

      Delete
  61. When I run this, the program exit with [gallery has stopped] error.
    What the problem is ?

    ReplyDelete
  62. Hi,
    When I am using this code on my Galaxy S5 device after image capture I will go to image crop view that's right.
    But on my Galaxy S5 after image capture I will go to image save option view .

    Please help..
    Thanks

    ReplyDelete
  63. Hi, thx for share your work. It's very interesting :)
    I test it now.
    I want after I've selected a picture (or taked a picture) to share this with differents services like G+/fb/email/sms/snapchat/twitter/other.
    I'm not abble to do this alone.
    Can you help me à little please ?

    I think I must use:
    "Intent sharingIntent = new Intent(Intent.ACTION_SEND);
    Uri screenshotUri = Uri.parse(path);

    sharingIntent.setType("image/png");
    sharingIntent.putExtra(Intent.EXTRA_STREAM, screenshotUri);
    startActivity(Intent.createChooser(sharingIntent, "Share image using"));"

    But I don't kno how

    ReplyDelete
  64. For me its not Working. camera working but gallery not displaying image. am using Samsung Galaxy GTS5303

    ReplyDelete
  65. Hi,
    I have executed this code but while I am executing this code I have an error when camera is opened as "Unfortunately stopped".
    Can suggest anyone on this

    ReplyDelete
  66. this is great but how to store that image in sqlite.. thats more imprtant thing

    ReplyDelete
  67. Nice Tutorial, but can you tell me why it's forced close everytime I take from camera, but it's works when I import from gallery.

    ReplyDelete
  68. Nice Tutorial, but when I select an image from the gallery, the main activity is opened and no cropping option appears. What do I do ?
    Thanks

    ReplyDelete
    Replies
    1. can you see the image on main activity? If no it's mean you are getting null as data on your onActivityResult. For that I will suggest to use URI and set into Imageview.

      Delete
  69. hello manish,

    nice work,it worked for me,but in my app I have crop an image already there in activity on click of button I have to crop that image.Can u help?

    ReplyDelete
  70. I am not getting my image on image view after clicking save button.plz help me out!

    ReplyDelete
  71. I want load image from Gallery and Camera or a url. please help for set mSource is in String format.

    ReplyDelete
  72. some device not work in crop image. I test motoe and asus.

    ReplyDelete