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<String> adapter = new ArrayAdapter<String> (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<CropOption> cropOptions = new ArrayList<CropOption>();<br /><br /><%%KEEPWHITESPACE%%> Intent intent = new Intent("com.android.camera.action.CROP");<br /><%%KEEPWHITESPACE%%> intent.setType("image/*");<br /><br /><%%KEEPWHITESPACE%%> List<ResolveInfo> 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 />[ad]
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
by
![]()
hi
thanks for the usefull post. but how can i use the cropped picture in other classes?
thanks again
Hi tom, you can save it into temporary file then load it from other class.
Image cropping is in square shape but how can crop in vowel shape ?
Squre shape is built in android crop function, you have to create your own implementation to create croping area other than square
hi any one know how crop and image as ovel shape…could u help me to reslove this problem….
Thanking you Adavance….
Ashwini:
Hai i am facing the same issue??how to crop in ovel shape do u get any results in that pls share it….
Thks in advance..
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?
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;
}
can any one tell me how to convert image in to pdf format in android
/*
* 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 */
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?
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;
}
}
Could you give me the log cat messages?
I have solved my problem.anyways thanks for ur support
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?
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?
hi, lorenz.
can i remove save/button so after i take a picture it always save to sdcard.
Yes you can skip the save button and directly save the bitmap to file
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.
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)
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
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.
Once again great example- saved time and worked without problems.
Thanx Janar…;)
Works fine for me. Thanks.
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?
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.
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?
After cropping there are ‘Save’ & ‘Discard’ buttons. How can I change the text on the button? Say, to ‘Done’ & ‘Cancel’.
You can’t change the button, that’s android built in app.
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.
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
thanks for your tutorial..
how if I want to crop image not from uri, but from created bitmap?
Thank you very much for the tutorial.
Your code is so clean and able to understand.
You are a hell of a android developer!!
Thanks for the tutorial, really nice work save time for me.
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
aashish:
I am facing a problem on cropping the image in ovel shape if u know that pls share it …
Thks in advance…
working great for gallery image cropping
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..
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.
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
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.
how to convert image in to pdf format in android?
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
Avoid using height and width in these line
intent.putExtra(“outputX”, width);
intent.putExtra(“outputY”, height);
intent.putExtra(“aspectX”, width);
intent.putExtra(“aspectY”, height);
Just pass ratios as 4:3, 16:9 for aspectx and aspecty.. where as pass values lesser than 300, when i used height and width gallery got force closed.. May be it happened because of the resolution of image being lesser than height and width of device[I am not sure].
Hope this helps you.. Correct me if I am wrong..
I meant use values lesser than 300 for outputX and OutputY in these lines
intent.putExtra(“outputX”, width);
intent.putExtra(“outputY”, height);
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….
hi any one know how crop an image as ovel shape can u help me for this….
SAME PROBLEM ??? if u get any thing pls share it…
Thks in advance.
Thank you very much Lorenz,
Great example and nice tutorial, You saved my time,
Greeting from Iran.
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?
Thanx Alot………………..
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..:)
Please recheck the page I have tried to solve your problem. Please see my posts
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
@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..
Define PhotoFeature class in your app. And onActivityResult(a,a,a).. is in the above code …
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 ….
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…
Is their any way to crop the exact face on cropping image????
anybody????
Please can tell me how to find the height and weight of crop images. I am try for many days.
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 ;
Hey lorenz , I’ve fixed that problem .
Hey lorenz , I want to add an image filter buttons at ImageCrop Intent .
How can I add it ??
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….
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 ???
Doesnt Seems to work on 2.2
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
This code is not working on Motorola devices.Is there any external parameter that i need to pass ??
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.
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?
The “com.android.camera.action.CROP” is not part of the public API and was removed.
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?
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?
Really thanks.Your code helps me to remove my stress.
Can anyone know me, how to use crop image to upload the server
You are great!!
Thousand thanks…
Good Tutorial, work fine, thanks a lot
Regards, Carlos
Complete solution thanks for tons !
lots of thx!
how to make the croped image resolution 1024×1024??
man you make my day
thanks thanks and thanks
really simple and good tuts
i am new to android. I want coding to crop the image in irregular shape.Thanks in advance.
Great tutorial .Thanks for this.
Thank you. it really helps
perfecto
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
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
It is nice example
You saved me hours of work. Thx 🙂
You are a life saver!!
How can i save the cropped image? Can i save that cropped image in gallery ?
Simplest tutorial showing how to capture images from camera or gallery. Thanks a lot!
It works. Thanks.
One doubt. How can i add a pinch zoom inside those rectangle
Its useful example..
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()
Hi Shridutt, thanks for the report. I don’t have kitkat device, hope can test it soon.
there seems to be a problem in kitkat for selecting image from gallery please see the following stackoverflow post:
http://stackoverflow.com/questions/20248178/kitkat-error-while-trying-to-load-an-image
Excellent! Thanks for this contribution.
When i captured images for this apps,this images add to my gallery and external sd.But i want to add these images only a external folder like viber,not into my photo gallery. Can i create a new folder for stoting captured images.And how can i find out the pixel value of cropped image