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...
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?
ReplyDeleteyes sure!
Deletejust 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,
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.
DeleteHi, No issue you can make me a detail mail my id is-manishsri01@gmail.com
DeleteThanks,
can we use explicit intent for cropping image
ReplyDeleteHello,
DeleteI 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...
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
DeleteThanks for sharing. It works!
ReplyDeleteYour welcome, and thanks for positive comment on my post..
Deletehi here in your code i want to change these two lines
ReplyDeleteintent.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.
Hi,
Deleteintent.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..
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.
ReplyDeleteFor 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.
DeleteAnd 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.
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
ReplyDeleteNo 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.
Deletethanks i will search if i get solution i will put answer in your blog
DeleteThank you so much!
Deletei want to know that how that rectangle is coming and how to get size of rectangle.
DeleteThis is depend upon android device density and size-
DeleteBasically 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);
This comment has been removed by the author.
ReplyDeleteHi, 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."
ReplyDeleteHi Jaden can you paste your error log here?
DeleteWell 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();
}
04-26 11:38:06.107: E/Trace(1834): error opening trace file: No such file or directory (2)
ReplyDelete04-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
and this as well ...
ReplyDelete04-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
As you can see-
DeleteCaused 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?
Ok. i will try it out. It crashes when i launch the app.
ReplyDeleteHi, 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.
ReplyDeletewhat was the issue?
Deletewell 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..
It is the package name - SimpleCameraGalleryDemo - name conflicted. I solved it as you said and manage to select from image gallery and crop it.
ReplyDeleteHowever, when i select camera, it crashes.
And for the above code you gave it to me.... where do i place it in my coding?
Okay so you can check this comment-
Deletehttp://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.
Do i add the above given comment code into the OnActivityResult method for camera??
ReplyDeleteand replace with the old ones that were given in the post?
ReplyDeleteP.S:
I apologized, i am just confused about the coding for the camera.
just change whole onActivityResult with new one..
DeleteHi see below code in my case I am using on button and dialog box for camera and gallery instead of two button-
Deletepublic 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);
}
}
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?
ReplyDeleteThis 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.
DeleteFor 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..
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.
ReplyDeleteHi yan!
ReplyDeleteLet 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?
hi manish, i am using a galaxy nexus.
ReplyDeleteso 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
yes may be remove some app from your phone and try again..and yes you are right problem is the high resolution image.
Deletehmm... tried so but still not able to run the program still
DeletePlease try to debug code using debugger I think you got null data that's why not able to get image after crop..
DeleteUse 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);
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.
Deletehi
ReplyDeleteIn 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
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-
Deletehttp://www.androidhub4you.com/2012/07/how-to-crop-image-from-camera-and.html?showComment=1366178156846#c3655311558111274569
I got code but when store in sd card image will going to distorting.
DeleteI 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.
ReplyDeleteyes 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..
Deletewhen i click on camera then camera open and take pick and when click on save my apps crashed and showing msg
ReplyDeletejava.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
As you can see your data is null that's why your application got crash..
DeleteI 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,
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
ReplyDeleteif (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
Hi it is becasuse of null data on press back button so please change your code-
Deleteprotected 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..
i have a problem, how can i save the image that has been crop into my phone gallery?
ReplyDeletethank you very much,
ReplyDeleteI 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 ?
I've tried the code on sony xperia s with android 4.0 it works without error.
DeleteYes Firas you are right I have also same issue its work on some devices and failed on some..
DeleteError is who==null;
I think it is because of high resolution image..
Please try it on google..
Ok thank you for the fast response,
DeleteI 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 :-)
I tested it on HTC 4.0 and Samsung Gallexy S Dues and its working fine..
DeletePlease check on google and if got answer please paste here so other people got help from you..
Thanks,
Thanks for your code.. but how can get exact path of cropped image. I want upload it to the server
ReplyDeleteHi I got same question on stackoverflow-
Deletesearch it on google- "stack overflow question number 14534625"
Thanks,
hi, can you tell me, how to pass the cropped image from one activity to another activity?
ReplyDeleteit showing classcastexception...
Hi, where I add bitmap into imageview from there call an intent for next page and put your image something like that-
DeleteIntent 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,
thank u so much.. it's working. i did a small mistake. thanks a lot..
ReplyDeleteYour welcome!
DeleteHey 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.....
ReplyDeleteuse web services follow my below post-
Deletehttp://www.androidhub4you.com/2012/09/consuming-rest-web-services-in-android.html
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:(
Yes sure i you have little issues you can ask..
DeleteHi Manish,
ReplyDeleteHow 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
Hi this is normally not happen so you can use canvas for it.
DeleteSee one of my comment on this post-
http://www.androidhub4you.com/2012/07/how-to-crop-image-from-camera-and.html?showComment=1366178156846#c3655311558111274569
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?
ReplyDeleteHi after cropping don't set your image in any imageview, just call web services for upload your image on server..
DeleteI 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
ReplyDeleteYes it is because of High resolution of Image...
DeleteDo you know how to get the coordinates(X,Y,H,W) of the cropped image?
ReplyDeleteIn my knowledge we can't get coordinate of crop image but we can set coordinate.
Deleteintent.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
Hi Manish,
ReplyDeleteThis 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?
Hi Satish,
DeleteThanks 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,
Hi Manish,
ReplyDeleteThis 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.
Hi Robin,
DeleteI think you should use canvas. It will help you to crop image in custom ratio like-circle,square etc.
can you help me,if you have any code
DeleteSorry dear I don't have any code. Just see this comment hope it will help you-
Deletehttp://www.androidhub4you.com/2012/07/how-to-crop-image-from-camera-and.html?showComment=1366178156846#c3655311558111274569
This comment has been removed by the author.
ReplyDeletevery fine code you upload
ReplyDeleteThanks Nadir!
DeleteHi 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..
ReplyDeletemy 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
hi, how can i get the best result of cropping image, so that the resolution of cropped image same as original ( quality)..
ReplyDeletethanks
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.
Deletecould you please send me the zip
ReplyDeletegetanoopwayanad@gmail.com
Sorry Anoop don't have code. Just copy from above it is very simple code...
DeleteThanks!
This comment has been removed by the author.
ReplyDeleteok...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..
ReplyDeletei think you got my problem......could you please help.
Yes yes just check for null data -
ReplyDeleteif (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!
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?
ReplyDeleteit is because of device density. It will be different-different on different devices.
DeleteMy system "photo crop" app working for crop but "Picture Crop" app is not responding when i click on save button...
ReplyDeleteDo 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();}
Hii M.S, I have problem with cropping a large image, its didn't work for more than 600 px image resolution
ReplyDeleteprotected 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;
}
}}
This comment has been removed by the author.
ReplyDeleteHi Manish,
ReplyDeleteThanx 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
So Simple just setonclicklistner on that imageview and on click open the camera and onActivityResult set image into imagview.
DeleteThanx 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.
ReplyDeleteWe have same croping code for both. So it should function same as well camera and gallery both.
DeleteIts not working the same way when i exactly copied ur code.U can also try and see.
ReplyDeleteits possible to get the multiple crop option an above code...pls share
ReplyDeleteHi Manish,
ReplyDeleteI have got problem for crop image. In Samsung galaxy tab , the selected URI give as null pointer exception,Please give me suggestion.
try below post-
Deletehttp://www.androidhub4you.com/2014/09/android-camera-onactivityresult-intent.html
Hi Manish
ReplyDeleteThe 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
Thanks a ton brother ! I don't have words to express my gratitude towards you ! Just thanks a ton again !
ReplyDeleteBro. 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..
ReplyDeleteyou need to shave your image into sdcard or sqlite, try below link-
Deletehttp://www.androidhub4you.com/2012/09/hello-friends-today-i-am-going-to-share.html
Hi Srivastava,
ReplyDeleteI 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...
Try something this-
DeleteBitmap 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.
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.
ReplyDeletei can't find the croping function when i run it
ReplyDeleteHi Manish,
ReplyDeleteAfter 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.
Hi Manish,
ReplyDeleteThanks 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!!
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.
DeleteWhen I run this, the program exit with [gallery has stopped] error.
ReplyDeleteWhat the problem is ?
Hi,
ReplyDeleteWhen 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
Hi, thx for share your work. It's very interesting :)
ReplyDeleteI 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
For me its not Working. camera working but gallery not displaying image. am using Samsung Galaxy GTS5303
ReplyDeleteHi,
ReplyDeleteI 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
this is great but how to store that image in sqlite.. thats more imprtant thing
ReplyDeleteNice 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.
ReplyDeleteNice Tutorial, but when I select an image from the gallery, the main activity is opened and no cropping option appears. What do I do ?
ReplyDeleteThanks
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.
DeleteThanks Manish :)
ReplyDeletenice example
Thanks bro :)
Deletehello manish,
ReplyDeletenice 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?
I am not getting my image on image view after clicking save button.plz help me out!
ReplyDeleteI want load image from Gallery and Camera or a url. please help for set mSource is in String format.
ReplyDeletesome device not work in crop image. I test motoe and asus.
ReplyDelete