I am using the following code to crop images from camera and gallery :
private void doCrop() {
final ArrayList<CropOption> cropOptions = new ArrayList<CropOption>();
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setType("image/*");
List<ResolveInfo> list = getPackageManager().queryIntentActivities(intent, 0);
int size = list.size();
if (size == 0) {
Toast.makeText(this, getApplicationContext().getString(R.string.crop_unavailable), Toast.LENGTH_SHORT).show();
// return
} else {
intent.setData(mImageCaptureUri);
int y = 200;
if(lastSelect == 1 || lastSelect == 2 || lastSelect == 3 || lastSelect == 4){
y = (int) (200 * 0.5697329376854599);
}
intent.putExtra("outputX", 200);
intent.putExtra("outputY", y);
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra("scale", true);
intent.putExtra("return-data", true);
if (size == 1) {
Intent i = new Intent(intent);
ResolveInfo res = list.get(0);
i.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
startActivityForResult(i, CROP_FROM_CAMERA);
} else {
for (ResolveInfo res: list) {
final CropOption co = new CropOption();
co.title = getPackageManager().getApplicationLabel(res.activityInfo.applicationInfo);
co.icon = getPackageManager().getApplicationIcon(res.activityInfo.applicationInfo);
co.appIntent = new Intent(intent);
co.appIntent.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
cropOptions.add(co);
}
CropOptionAdapter adapter = new CropOptionAdapter(getApplicationContext(), cropOptions);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(getApplicationContext().getString(R.string.select_crop_app));
builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
startActivityForResult(cropOptions.get(item).appIntent, CROP_FROM_CAMERA);
}
});
builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
if (mImageCaptureUri != null) {
getContentResolver().delete(mImageCaptureUri, null, null);
mImageCaptureUri = null;
}
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
}
While it crops pictures from camera well, it doesn't work on gallery images. It always returns basic picture selected from gallery.
onActivityResult :
if (resultCode != RESULT_OK)
return;
switch (requestCode) {
case PICK_FROM_CAMERA:
doCrop();
break;
case PICK_FROM_FILE:
mImageCaptureUri = data.getData();
doCrop();
break;
case CROP_FROM_CAMERA:
Bundle extras = data.getExtras();
if (extras != null) {
photo = extras.getParcelable("data");
// imgImage4.setImageBitmap(photo);
int w = (int) (UIHelpers.width * 0.15);
File f = new File(mImageCaptureUri.getPath());
if (f.exists()) {
// f.delete();
}
String imageDir = getRealPathFromURI(mImageCaptureUri);
txtSelectLogoNj.setVisibility(View.GONE);
rlLogoNj.setVisibility(View.VISIBLE);
image5 = imageDir;
App.sharedpreferences = getSharedPreferences(App.MyPREFERENCES, Context.MODE_PRIVATE);
App.editor = App.sharedpreferences.edit();
App.editor.putString("IMAGE5", imageDir);
App.editor.commit();
}
}
break;
}
How do I fix it?
please use library project for crop image form camera or gallery .
perfect it will work.
https://github.com/biokys/cropimage
Try this Working code
Buttonclick to take camera
dialog.show();
Add this inside Oncreate()
captureImageInitialization();
try this it will work
// for camera
private void captureImageInitialization() {
try {
/**
* a selector dialog to display two image source options, from
* camera ‘Take from camera’ and from existing files ‘Select from
* gallery’
*/
final String[] items = new String[] { "Take from camera",
"Select from gallery" };
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.select_dialog_item, items);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Select Image");
builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) { // pick
// from
// camera
if (item == 0) {
/**
* To take a photo from camera, pass intent action
* ‘MediaStore.ACTION_IMAGE_CAPTURE‘ to open the camera
* app.
*/
Intent intent = new Intent(
MediaStore.ACTION_IMAGE_CAPTURE);
/**
* 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.
*/
mImageCaptureUri = Uri.fromFile(new File(Environment
.getExternalStorageDirectory(), "tmp_avatar_"
+ String.valueOf(System.currentTimeMillis())
+ ".jpg"));
intent.putExtra(
android.provider.MediaStore.EXTRA_OUTPUT,
mImageCaptureUri);
try {
intent.putExtra("return-data", true);
// intent.putExtra("return-data1", true);
startActivityForResult(intent, PICK_FROM_CAMERA);
// finish();
} catch (ActivityNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
} else {
// pick from file
/**
* 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.
*/
/*
* Intent intent = new Intent();
*
* intent.setType("image/*");
* intent.setAction(Intent.ACTION_GET_CONTENT);
*
* startActivityForResult(Intent.createChooser(intent,
* "Complete action using"), PICK_FROM_FILE);
*/
try {
Intent intent = new Intent();
intent = new Intent(Intent.ACTION_PICK);
intent.setType("*/*");
intent.putExtra(
android.provider.MediaStore.EXTRA_OUTPUT,
mImageCaptureUri);
startActivityForResult(Intent.createChooser(intent,
"Complete action using"), PICK_FROM_FILE);
} catch (Exception e) {
e.printStackTrace();
}
}
}
});
dialog = builder.create();
} catch (Exception e) {
e.printStackTrace();
} catch (OutOfMemoryError o) {
o.printStackTrace();
}
}
public class CropOptionAdapter extends ArrayAdapter<CropOption> {
private ArrayList<CropOption> mOptions;
private LayoutInflater mInflater;
public CropOptionAdapter(Context context, ArrayList<CropOption> options) {
super(context, R.layout.crop_selector, options);
mOptions = options;
mInflater = LayoutInflater.from(context);
}
#Override
public View getView(int position, View convertView, ViewGroup group) {
// new try
try {
if (convertView == null)
convertView = mInflater.inflate(R.layout.crop_selector,
null);
CropOption item = mOptions.get(position);
if (item != null) {
((ImageView) convertView.findViewById(R.id.iv_icon))
.setImageDrawable(item.icon);
((TextView) convertView.findViewById(R.id.tv_name))
.setText(item.title);
return convertView;
}
return null;
} catch (Exception e) {
e.printStackTrace();
}
if (convertView == null)
convertView = mInflater.inflate(R.layout.crop_selector, null);
CropOption item = mOptions.get(position);
if (item != null) {
((ImageView) convertView.findViewById(R.id.iv_icon))
.setImageDrawable(item.icon);
((TextView) convertView.findViewById(R.id.tv_name))
.setText(item.title);
return convertView;
}
return null;
}
}
public class CropOption {
public CharSequence title;
public Drawable icon;
public Intent appIntent;
}
// Method for Crop
private void doCrop() {
try {
final ArrayList<CropOption> cropOptions = new ArrayList<CropOption>();
/**
* Open image crop app by starting an intent
* ‘com.android.camera.action.CROP‘.
*/
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setType("image/*");
/**
* Check if there is image cropper app installed.
*/
List<ResolveInfo> list = getPackageManager().queryIntentActivities(
intent, 0);
int size = list.size();
/**
* If there is no image cropper app, display warning message
*/
if (size == 0) {
Toast.makeText(this, "Can not find image crop app",
Toast.LENGTH_SHORT).show();
return;
} else {
/**
* Specify the image path, crop dimension and scale
*/
intent.setData(mImageCaptureUri);
intent.putExtra("outputX", 300);
intent.putExtra("outputY", 300);
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra("scale", true);
intent.putExtra("return-data", true);
/**
* 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.
*/
if (size == 1) {
Intent i = new Intent(intent);
ResolveInfo res = list.get(0);
i.setComponent(new ComponentName(
res.activityInfo.packageName, res.activityInfo.name));
startActivityForResult(i, CROP_FROM_CAMERA);
} else {
/**
* If there are several app exist, create a custom chooser
* to let user selects the app.
*/
for (ResolveInfo res : list) {
final CropOption co = new CropOption();
co.title = getPackageManager().getApplicationLabel(
res.activityInfo.applicationInfo);
co.icon = getPackageManager().getApplicationIcon(
res.activityInfo.applicationInfo);
co.appIntent = new Intent(intent);
co.appIntent.setComponent(new ComponentName(
res.activityInfo.packageName,
res.activityInfo.name));
cropOptions.add(co);
}
CropOptionAdapter adapter = new CropOptionAdapter(
getApplicationContext(), cropOptions);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Choose Crop App");
builder.setAdapter(adapter,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int item) {
startActivityForResult(
cropOptions.get(item).appIntent,
CROP_FROM_CAMERA);
}
});
builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
if (mImageCaptureUri != null) {
getContentResolver().delete(mImageCaptureUri,
null, null);
mImageCaptureUri = null;
}
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
}
catch (Exception e) {
Log.e("Error", "ERROR IN CODE:" + e.toString());
e.printStackTrace();
}
}
onActivityResult :
if (requestCode == PICK_FROM_CAMERA) {
doCrop();
}
else if (requestCode == PICK_FROM_FILE) {
mImageCaptureUri = intent.getData();
doCrop();
}
else if (requestCode == CROP_FROM_CAMERA) {
Bundle extras = intent.getExtras();
/**
* After cropping the image, get the bitmap of the cropped image and
* display it on imageview.
*/
if (extras != null) {
Bitmap photo = extras.getParcelable("data");
// Camera Output
viewImage.setImageBitmap(photo);
ContextWrapper cw = new ContextWrapper(getApplicationContext());
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File directory1 = cw.getDir("Picture",Context.MODE_PRIVATE);
File mypath1 = new File(directory1, imageFileName + ".png");
picturepath = mypath1.toString();
// FileOutputStream fos = null;
try {
// fos = openFileOutput(filename, Context.MODE_PRIVATE);
System.out.println("mypath = " + mypath1);
fos = new FileOutputStream(mypath1);
// Use the compress method on the BitMap object to write
// image to the OutputStream
photo.compress(Bitmap.CompressFormat.PNG, 100, fos);
try {
fos.flush();
fos.close();
} catch (IOException e1) {
e1.printStackTrace();
}
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
Hi Can u Try this,
#Override
public void onActivityResult(final int requestCode, int resultCode,
Intent data) {
try {
switch (requestCode) {
case GALLERY_PIC_REQUEST:
if (resultCode == RESULT_OK) {
try {
picUri = data.getData();
System.out.println("Image Path::> "+picUri.getPath());
performCrop();
} catch (Exception e) {
ShowDialog_Ok("Error", "Couldn't load photo");
}
}
break;
case CAMERA_PIC_REQUEST:
if (resultCode == RESULT_OK) {
try {
picUri = data.getData();
System.out.println("Image Path::> "+picUri.getPath());
performCrop();
} catch (Exception e) {
ShowDialog_Ok("Error", "Couldn't load photo");
}
}
break;
case CROP_PIC_REQUEST:
Bitmap bitmap;
String path = "";
if (resultCode == RESULT_OK) {
String oldPath = fashionlyPreferences.getImagePath();
try {
picUri = data.getData();
path = Helper.GetPathFromURI(context, picUri);
bitmap = BitmapFactory.decodeFile(path);
Img_View.setImageBitmap(bitmap);
} catch (Exception e) {
ShowDialog_Ok("Error", "Couldn't load photo");
}
}
break;
}
} catch (Exception e) {
}
}
//Function for Crop
private void performCrop() {
// take care of exceptions
try {
if (picUri!=null) {
Intent cropIntent = new Intent("com.android.camera.action.CROP");
cropIntent.setDataAndType(picUri, "image/*");
cropIntent.putExtra("crop", "true");
cropIntent.putExtra("scale", true);
cropIntent.putExtra("aspectX", 0);
cropIntent.putExtra("aspectY", 0);
//cropIntent.putExtra("outputX", 400);
// cropIntent.putExtra("outputY", 400);
cropIntent.putExtra("return-data", false);
startActivityForResult(cropIntent, CROP_PIC_REQUEST);
}
}
// respond to users whose devices do not support the crop action
catch (ActivityNotFoundException anfe) {
Toast.makeText(this, "This device doesn't support the crop action!", Toast.LENGTH_SHORT).show();
}
}
Related
I have an app with image cropping option. After cropping the actual image, the cropped image is saved in gallery. My question is how to retrieve the file name and path of the cropped image saved in gallery.
my code is,
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final String [] items = new String [] {"Take from camera", "Select from gallery"};
ArrayAdapter<String> adapter = new ArrayAdapter<String> (this, android.R.layout.select_dialog_item,items);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Select Image");
builder.setAdapter( adapter, new DialogInterface.OnClickListener() {
public void onClick( DialogInterface dialog, int item ) { //pick from camera
if (item == 0) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
mImageCaptureUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(),
"tmp_avatar_" + String.valueOf(System.currentTimeMillis()) + ".jpg"));
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, mImageCaptureUri);
try {
intent.putExtra("return-data", true);
startActivityForResult(intent, PICK_FROM_CAMERA);
} catch (ActivityNotFoundException e) {
e.printStackTrace();
}
} else { //pick from file
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Complete action using"), PICK_FROM_FILE);
}
}
} );
final AlertDialog dialog = builder.create();
Button button = (Button) findViewById(R.id.btn_crop);
mImageView = (ImageView) findViewById(R.id.iv_photo);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.show();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK) return;
switch (requestCode) {
case PICK_FROM_CAMERA:
doCrop();
break;
case PICK_FROM_FILE:
mImageCaptureUri = data.getData();
doCrop();
break;
case CROP_FROM_CAMERA:
Bundle extras = data.getExtras();
if (extras != null) {
Bitmap photo = extras.getParcelable("data");
mImageView.setImageBitmap(photo);
}
File f = new File(mImageCaptureUri.getPath());
if (f.exists()) f.delete();
break;
}
}
private void doCrop() {
final ArrayList<CropOption> cropOptions = new ArrayList<CropOption>();
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setType("image/*");
List<ResolveInfo> list = getPackageManager().queryIntentActivities( intent, 0 );
int size = list.size();
if (size == 0) {
Toast.makeText(this, "Can not find image crop app", Toast.LENGTH_SHORT).show();
return;
} else {
intent.setData(mImageCaptureUri);
intent.putExtra("outputX", 200);
intent.putExtra("outputY", 200);
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra("scale", true);
intent.putExtra("return-data", true);
if (size == 1) {
Intent i = new Intent(intent);
ResolveInfo res = list.get(0);
i.setComponent( new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
startActivityForResult(i, CROP_FROM_CAMERA);
} else {
for (ResolveInfo res : list) {
final CropOption co = new CropOption();
co.title = getPackageManager().getApplicationLabel(res.activityInfo.applicationInfo);
co.icon = getPackageManager().getApplicationIcon(res.activityInfo.applicationInfo);
co.appIntent= new Intent(intent);
co.appIntent.setComponent( new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
cropOptions.add(co);
}
CropOptionAdapter adapter = new CropOptionAdapter(getApplicationContext(), cropOptions);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Choose Crop App");
builder.setAdapter( adapter, new DialogInterface.OnClickListener() {
public void onClick( DialogInterface dialog, int item ) {
startActivityForResult( cropOptions.get(item).appIntent, CROP_FROM_CAMERA);
}
});
builder.setOnCancelListener( new DialogInterface.OnCancelListener() {
#Override
public void onCancel( DialogInterface dialog ) {
if (mImageCaptureUri != null ) {
getContentResolver().delete(mImageCaptureUri, null, null );
mImageCaptureUri = null;
}
}
} );
AlertDialog alert = builder.create();
alert.show();
}
}
}
I have tried a lot but not retrieving the file name and path. Is there any solution.
You are using startActivityForResult(), but do you override onActivityResult()? In your case you need to do the following:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == PICK_FROM_FILE && resultCode == RESULT_OK)
{
Uri pictureUri = data.getData();
}
}
This code gets the Uri of the picture. Then you can use this Uri to get the path, using a method like below:
private String getRealPathFromURI(Context context, Uri contentUri)
{
Cursor cursor = null;
try
{
String[] proj = {MediaStore.Images.Media.DATA};
cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} finally
{
if (cursor != null)
{
cursor.close();
}
}
}
EDIT
After you crop the Bitmap and ready to go, you can save it with something like this:
private Uri saveOutput(Bitmap croppedImage)
{
Uri saveUri = null;
// Saves the image in cache, you may want to modify this to save it to Gallery
File file = new File(getCacheDir(), "cropped");
OutputStream outputStream = null;
try
{
file.getParentFile().mkdirs();
saveUri = Uri.fromFile(file);
outputStream = getContentResolver().openOutputStream(saveUri);
if (outputStream != null)
{
croppedImage.compress(Bitmap.CompressFormat.JPEG, 90, outputStream);
}
} catch (IOException e)
{
// log the error
}
return saveUri;
}
After getting the Uri, you can get path to cropped image with the same method above.
I am trying to pick and crop a picture directly from the gallery,
for some reason the crop intent doesn't always work, on some devices its working with the stock gallery,
and on some devices its working only with unofficial gallery apps (like my G2).
I know it should work on my device because i have other apps that use the same gallery crop function and its works.
every time i try to open the intent with the stock gallery i get the following message: couldn't find item
(I want the user to pick the image, not pass specific image location)
// Start a intent to get event image from the user
private void getCroppedImage(){
// Create an output directory for the image
String timeStamp = new SimpleDateFormat("ddMMMyy_HHmmSSS").format(new Date());
File dir = new File(Environment.getExternalStorageDirectory ()
+ File.separator
+ "MyApp/Images");
File picPath = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
File outputPath = new File(dir,"IMG_"+ timeStamp + ".jpg");
// Make sure that the output dir exists
if (!dir.exists()){
dir.mkdirs();
}
// Start intent, if available
Intent cropIntent = new Intent("com.android.camera.action.CROP");
//cropIntent.setData(Uri.fromFile(picPath));
cropIntent.setType("image/*");
cropIntent.putExtra("crop", "true");
cropIntent.putExtra("outputX", 512);
cropIntent.putExtra("outputY", 512);
cropIntent.putExtra("aspectX", 1);
cropIntent.putExtra("aspectY", 1);
cropIntent.putExtra("output", Uri.fromFile(outputPath));
// Verify that the intent will resolve to an activity
if (cropIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(cropIntent, REQUEST_CODE_CROP_IMAGE);
}else{
cropIntent.setAction(Intent.ACTION_GET_CONTENT);
// Verify that the intent will resolve to an activity
if (cropIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(cropIntent, REQUEST_CODE_GET_PICTURE);
}else{
Toast.makeText(this,"Gallery not detected",Toast.LENGTH_LONG).show();
}
}
}
any thoughts?
try this:
public class CropOptionAdapter extends ArrayAdapter<CropOption> {
private ArrayList<CropOption> mOptions;
private LayoutInflater mInflater;
public CropOptionAdapter(Context context, ArrayList<CropOption> options) {
super(context, R.layout.crop_selector, options);
mOptions = options;
mInflater = LayoutInflater.from(context);
}
#Override
public View getView(int position, View convertView, ViewGroup group) {
if (convertView == null)
convertView = mInflater.inflate(R.layout.crop_selector, null);
CropOption item = mOptions.get(position);
if (item != null) {
((ImageView) convertView.findViewById(R.id.iv_icon))
.setImageDrawable(item.icon);
((TextView) convertView.findViewById(R.id.tv_name))
.setText(item.title);
return convertView;
}
return null;
}
}
public class CropOption {
public CharSequence title;
public Drawable icon;
public Intent appIntent;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK)
return;
switch (requestCode) {
case PICK_FROM_CAMERA:
/**
* After taking a picture, do the crop
*/
doCrop();
break;
case PICK_FROM_FILE:
/**
* After selecting image from files, save the selected path
*/
mImageCaptureUri = data.getData();
infoLog("pick from file");
doCrop();
break;
case CROP_FROM_CAMERA:
Bundle extras = data.getExtras();
/**
* After cropping the image, get the bitmap of the cropped image and
* display it on imageview.
*/
if (extras != null) {
photo = extras.getParcelable("data");
Bitmap circleBitmap = Bitmap.createBitmap(photo.getWidth(),
photo.getHeight(), Bitmap.Config.ARGB_8888);
BitmapShader shader = new BitmapShader(photo, TileMode.CLAMP,
TileMode.CLAMP);
Paint paint = new Paint();
paint.setShader(shader);
Canvas c = new Canvas(circleBitmap);
c.drawCircle(photo.getWidth() / 2, photo.getHeight() / 2,
photo.getWidth() / 2, paint);
img.setImageBitmap(photo);
}
File f = new File(mImageCaptureUri.getPath());
/**
* Delete the temporary image
*/
if (f.exists())
f.delete();
break;
}
}
private void doCrop() {
final ArrayList<CropOption> cropOptions = new ArrayList<CropOption>();
/**
* Open image crop app by starting an intent
* ‘com.android.camera.action.CROP‘.
*/
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setType("image/*");
/**
* Check if there is image cropper app installed.
*/
List<ResolveInfo> list = getPackageManager().queryIntentActivities(
intent, 0);
int size = list.size();
/**
* If there is no image cropper app, display warning message
*/
if (size == 0) {
Toast.makeText(this, "Can not find image crop app",
Toast.LENGTH_SHORT).show();
return;
} else {
/**
* Specify the image path, crop dimension and scale
*/
intent.setData(mImageCaptureUri);
intent.putExtra("outputX", 200);
intent.putExtra("outputY", 200);
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra("scale", true);
intent.putExtra("return-data", true);
/**
* There is possibility 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.
*/
if (size == 1) {
Intent i = new Intent(intent);
ResolveInfo res = list.get(0);
i.setComponent(new ComponentName(res.activityInfo.packageName,
res.activityInfo.name));
startActivityForResult(i, CROP_FROM_CAMERA);
} else {
/**
* If there are several app exist, create a custom chooser to
* let user selects the app.
*/
for (ResolveInfo res : list) {
final CropOption co = new CropOption();
co.title = getPackageManager().getApplicationLabel(
res.activityInfo.applicationInfo);
co.icon = getPackageManager().getApplicationIcon(
res.activityInfo.applicationInfo);
co.appIntent = new Intent(intent);
co.appIntent
.setComponent(new ComponentName(
res.activityInfo.packageName,
res.activityInfo.name));
cropOptions.add(co);
}
CropOptionAdapter adapter = new CropOptionAdapter(
getApplicationContext(), cropOptions);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Choose Crop App");
builder.setAdapter(adapter,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
startActivityForResult(
cropOptions.get(item).appIntent,
CROP_FROM_CAMERA);
}
});
builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
if (mImageCaptureUri != null) {
getContentResolver().delete(mImageCaptureUri, null,
null);
mImageCaptureUri = null;
}
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
}
Problem:
I am fetching image from gallery and after that cropped that image and its working perfect in all device. But it is giving me error while running in Nexus 7 kitkat since i have checked build version for it with "Gallery Stopped" error. I have implemented code and all other neccessary permission in manifest file still not getting response. So can anybody resolve this?
Here is my Code:
final String[] items = new String[] { "Take from camera",
"Select from gallery" };
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.select_dialog_item, items);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Select Image");
builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) { // pick from
// camera
if (item == 0) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
mImageCaptureUri = Uri.fromFile(new File(Environment
.getExternalStorageDirectory(), "tmp_avatar_"
+ String.valueOf(System.currentTimeMillis())
+ ".jpg"));
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT,
mImageCaptureUri);
try {
intent.putExtra("return-data", true);
startActivityForResult(intent, PICK_FROM_CAMERA);
} catch (ActivityNotFoundException e) {
e.printStackTrace();
}
} else { // pick from file
Intent intent;
if (Build.VERSION.SDK_INT < 19) {
intent = new Intent();
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
startActivityForResult(Intent.createChooser(intent,
"Complete action using"), PICK_FROM_FILE);
} else {
intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("*/*");
startActivityForResult(Intent.createChooser(intent,
"Complete action using"), PICK_FROM_FILE);
}
/*
* Intent intent = new Intent();
*
* intent.setType("image/*");
* intent.setAction(Intent.ACTION_GET_CONTENT);
*
* startActivityForResult(Intent.createChooser(intent,
* "Complete action using"), PICK_FROM_FILE);
*/
}
}
});
final AlertDialog dialog = builder.create();
btnTakephoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.show();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK)
return;
switch (requestCode) {
case PICK_FROM_CAMERA:
doCrop();
break;
case PICK_FROM_FILE:
if (Build.VERSION.SDK_INT < 19) {
mImageCaptureUri = data.getData();
} else {
mImageCaptureUri = data.getData();
ParcelFileDescriptor parcelFileDescriptor;
try {
parcelFileDescriptor = getContentResolver()
.openFileDescriptor(mImageCaptureUri, "r");
FileDescriptor fileDescriptor = parcelFileDescriptor
.getFileDescriptor();
myBitmap = BitmapFactory
.decodeFileDescriptor(fileDescriptor);
parcelFileDescriptor.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
doCrop();
break;
case CROP_FROM_CAMERA:
Bundle extras = data.getExtras();
if (extras != null) {
myBitmap = extras.getParcelable("data");
}
File f = new File(mImageCaptureUri.getPath());
if (f.exists()) {
f.delete();
}
ByteArrayOutputStream stream = new ByteArrayOutputStream();
myBitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byteArray = stream.toByteArray();
Intent n = new Intent();
n.setClass(getApplicationContext(), EffectsActivity.class);
n.putExtra("picture", byteArray);
startActivity(n);
break;
}
}
private void doCrop() {
final ArrayList<CropOption> cropOptions = new ArrayList<CropOption>();
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setType("image/*");
List<ResolveInfo> list = getPackageManager().queryIntentActivities(
intent, 0);
int size = list.size();
if (size == 0) {
Toast.makeText(this, "Can not find image crop app",
Toast.LENGTH_SHORT).show();
return;
} else {
if (mImageCaptureUri != null) {
intent.setData(mImageCaptureUri);
}
intent.putExtra("outputX", 350);
intent.putExtra("outputY", 350);
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra("scale", true);
intent.putExtra("return-data", true);
if (size == 1) {
Intent i = new Intent(intent);
ResolveInfo res = list.get(0);
i.setComponent(new ComponentName(res.activityInfo.packageName,
res.activityInfo.name));
startActivityForResult(i, CROP_FROM_CAMERA);
} else {
for (ResolveInfo res : list) {
final CropOption co = new CropOption();
co.title = getPackageManager().getApplicationLabel(
res.activityInfo.applicationInfo);
co.icon = getPackageManager().getApplicationIcon(
res.activityInfo.applicationInfo);
co.appIntent = new Intent(intent);
co.appIntent
.setComponent(new ComponentName(
res.activityInfo.packageName,
res.activityInfo.name));
cropOptions.add(co);
}
CropOptionAdapter adapter = new CropOptionAdapter(
getApplicationContext(), cropOptions);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Choose Crop App");
builder.setAdapter(adapter,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
startActivityForResult(
cropOptions.get(item).appIntent,
CROP_FROM_CAMERA);
}
});
builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
if (mImageCaptureUri != null) {
getContentResolver().delete(mImageCaptureUri, null,
null);
mImageCaptureUri = null;
}
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
CropAction:
public class CropOption {
public CharSequence title;
public Drawable icon;
public Intent appIntent;
}
CropOptionAdapter.java
public class CropOptionAdapter extends ArrayAdapter<CropOption> {
private ArrayList<CropOption> mOptions;
private LayoutInflater mInflater;
public CropOptionAdapter(Context context, ArrayList<CropOption> options) {
super(context, R.layout.crop_selector, options);
mOptions = options;
mInflater = LayoutInflater.from(context);
}
#Override
public View getView(int position, View convertView, ViewGroup group) {
if (convertView == null)
convertView = mInflater.inflate(R.layout.crop_selector, null);
CropOption item = mOptions.get(position);
if (item != null) {
((ImageView) convertView.findViewById(R.id.iv_icon))
.setImageDrawable(item.icon);
((TextView) convertView.findViewById(R.id.tv_name))
.setText(item.title);
return convertView;
}
return null;
}
}
To resolve the problem what i have done is to,
just change the code from this
intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("*/*");
startActivityForResult(
Intent.createChooser(intent, "Complete action using"), PICK_FROM_FILE
);
to
intent = new Intent(Intent.ACTION_PICK);
intent.setType("*/*");
intent.putExtra(
android.provider.MediaStore.EXTRA_OUTPUT, mImageCaptureUri
);
startActivityForResult(
Intent.createChooser(intent, "Complete action using"), PICK_FROM_FILE
);
Working like charm.
Hi i can able to crop image either rectangle shape or vowel shape,here in both case 4 coordiante points based those points we are cropping image those are left middle point,right side middle point,top and bottom middle point but,my requirement is i need to crop image based on 8 coordinates,what above i mentioned those 4 coordinates and remain 4 is top of image starting edge 1 coordinate and top of image ending corner 1 coordinate,bottom of image starting one coordinate,ending of image another coordidnate,then image we can crop different shapes,so i don't know how to crop images using 8 coordinates...using below code i can able crop image using 4 coordinates....any one help me please
MainActivity .class:
public class MainActivity extends Activity {
private Uri mImageCaptureUri;
private ImageView mImageView;
private static final int PICK_FROM_CAMERA = 1;
private static final int CROP_FROM_CAMERA = 2;
private static final int PICK_FROM_FILE = 3;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final String [] items = new String [] {"Take from camera", "Select from gallery"};
ArrayAdapter<String> adapter = new ArrayAdapter<String> (this, android.R.layout.select_dialog_item,items);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Select Image");
builder.setAdapter( adapter, new DialogInterface.OnClickListener() {
public void onClick( DialogInterface dialog, int item ) { //pick from camera
if (item == 0) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
mImageCaptureUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(),
"tmp_avatar_" + String.valueOf(System.currentTimeMillis()) + ".jpg"));
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, mImageCaptureUri);
try {
intent.putExtra("return-data", true);
startActivityForResult(intent, PICK_FROM_CAMERA);
} catch (ActivityNotFoundException e) {
e.printStackTrace();
}
} else { //pick from file
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Complete action using"), PICK_FROM_FILE);
}
}
} );
final AlertDialog dialog = builder.create();
Button button = (Button) findViewById(R.id.btn_crop);
mImageView = (ImageView) findViewById(R.id.iv_photo);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.show();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK) return;
switch (requestCode) {
case PICK_FROM_CAMERA:
doCrop();
break;
case PICK_FROM_FILE:
mImageCaptureUri = data.getData();
doCrop();
break;
case CROP_FROM_CAMERA:
Bundle extras = data.getExtras();
if (extras != null) {
Bitmap photo = extras.getParcelable("data");
mImageView.setImageBitmap(photo);
}
File f = new File(mImageCaptureUri.getPath());
if (f.exists()) f.delete();
break;
}
}
private void doCrop() {
final ArrayList<CropOption> cropOptions = new ArrayList<CropOption>();
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setType("image/*");
List<ResolveInfo> list = getPackageManager().queryIntentActivities( intent, 0 );
int size = list.size();
if (size == 0) {
Toast.makeText(this, "Can not find image crop app", Toast.LENGTH_SHORT).show();
return;
} else {
intent.setData(mImageCaptureUri);
intent.putExtra("outputX", 200);
intent.putExtra("outputY", 200);
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra("scale", true);
intent.putExtra("return-data", true);
if (size == 1) {
Intent i = new Intent(intent);
ResolveInfo res = list.get(0);
i.setComponent( new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
startActivityForResult(i, CROP_FROM_CAMERA);
} else {
for (ResolveInfo res : list) {
final CropOption co = new CropOption();
co.title = getPackageManager().getApplicationLabel(res.activityInfo.applicationInfo);
co.icon = getPackageManager().getApplicationIcon(res.activityInfo.applicationInfo);
co.appIntent= new Intent(intent);
co.appIntent.setComponent( new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
cropOptions.add(co);
}
CropOptionAdapter adapter = new CropOptionAdapter(getApplicationContext(), cropOptions);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Choose Crop App");
builder.setAdapter( adapter, new DialogInterface.OnClickListener() {
public void onClick( DialogInterface dialog, int item ) {
startActivityForResult( cropOptions.get(item).appIntent, CROP_FROM_CAMERA);
}
});
builder.setOnCancelListener( new DialogInterface.OnCancelListener() {
#Override
public void onCancel( DialogInterface dialog ) {
if (mImageCaptureUri != null ) {
getContentResolver().delete(mImageCaptureUri, null, null );
mImageCaptureUri = null;
}
}
} );
AlertDialog alert = builder.create();
alert.show();
}
}
}
I am trying to let to user crop images after taking them / choosing from gallery. Now, the cropping after selecting from gallery works but not camera. Below are my codes, I am not getting any error message. We followed http://mobile.tutsplus.com/tutorials/android/capture-and-crop-an-image-with-the-device-camera/
//Camera button clicked
public void camera_click(View view) {
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra("return-data", true);
startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);
}
//Result of camera capture
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
//camera
if (requestCode == CAMERA_PIC_REQUEST) {
mImageCaptureUri = data.getData();
performCrop();
}
if (requestCode == PIC_CROP) {
//get the returned data
try{
Bundle extras = data.getExtras();
//get the cropped bitmap
thumbnail = extras.getParcelable("data");
//retrieve a reference to the ImageView
ImageView image = (ImageView) findViewById(R.id.test_image);
//display the returned cropped image
image.setImageBitmap(thumbnail);
TextView imgTv = (TextView) findViewById(R.id.imageInfo);
String desc = imgTv.getText().toString();
if (desc.equalsIgnoreCase("")) {
String errorMessage = "Please enter a description before submitting a photo.";
Toast toast = Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT);
toast.show();
} else {
}
}
catch(Exception ex)
{
Log.i("err", ex.getMessage());
}
}
//gallery selected
if (requestCode == SELECT_PHOTO) {
if (data != null) {
Cursor cursor = getContentResolver().query(data.getData(), null, null, null, null);
cursor.moveToFirst(); //if not doing this, 01-22 19:17:04.564: ERROR/AndroidRuntime(26264): Caused by: android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 1
int idx = cursor.getColumnIndex(ImageColumns.DATA);
String fileSrc = cursor.getString(idx);
thumbnail = BitmapFactory.decodeFile(fileSrc); //load preview image
thumbnail = android.graphics.Bitmap.createScaledBitmap(thumbnail, 100, 100, true);
// ImageView image = (ImageView) findViewById(R.id.test_image);
// image.setImageBitmap(thumbnail);
ImageButton cam = (ImageButton) findViewById(R.id.camera);
// cam.setVisibility(View.INVISIBLE);
ImageButton gal = (ImageButton) findViewById(R.id.gallery);
mImageCaptureUri = data.getData();
// gal.setVisibility(View.INVISIBLE);
performCrop();
} else {
//Log.d(LOG_TAG, "idButSelPic Photopicker canceled");
// m_Tv.setText("Image selection canceled!");
}
}
}
}//end onactivity results
//method to luanch crop image
private void performCrop() {
try {
//call the standard crop action intent (the user device may not support it)
Intent cropIntent = new Intent("com.android.camera.action.CROP");
cropIntent.setDataAndType(mImageCaptureUri, "image/*");
//set crop properties
cropIntent.putExtra("crop", "true");
//indicate aspect of desired crop
cropIntent.putExtra("aspectX", 1);
cropIntent.putExtra("aspectY", 1);
//indicate output X and Y
cropIntent.putExtra("outputX", 256);
cropIntent.putExtra("outputY", 256);
//retrieve data on return
cropIntent.putExtra("return-data", true);
//start the activity - we handle returning in onActivityResult
startActivityForResult(cropIntent, PIC_CROP);
} catch (ActivityNotFoundException anfe) {
//display an error message
Log.i("err", anfe.getLocalizedMessage());
String errorMessage = "Your device doesn't support the crop action!";
Toast toast = Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT);
toast.show();
Intent myIntent = new Intent();
startActivityForResult(myIntent, PIC_CROP);
}
}
This line is probably giving you this problem:
mImageCaptureUri = data.getData();
Delete this and check it out.
If not, I could give you a working code.
Working sample:
Include also this library: https://github.com/lvillani/android-cropimage
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
switch (requestCode) {
case PICK_FROM_CAMERA:
doCrop();
break;
case PICK_FROM_FILE:
if(data != null){
mImageCaptureUri = data.getData();
doCrop();
}
break;
case CROP_FROM_CAMERA:
if(data != null){
Bundle extras = data.getExtras();
if (extras != null) {
Bitmap photo = extras.getParcelable("data");
imagebutton.setImageBitmap(photo);
imagebutton.setScaleType(ScaleType.FIT_XY);
}
File f = new File(mImageCaptureUri.getPath());
if (f.exists()) f.delete();
}
break;
}
}
private void doCrop() {
// TODO Auto-generated method stub
final ArrayList<CropOption> cropOptions = new ArrayList<CropOption>();
Intent intent = new Intent("com.android.camera.action.CROP");
// intent.setClassName("com.android.camera", "com.android.camera.CropImage");
intent.setType("image/*");
List<ResolveInfo> list = getActivity().getPackageManager().queryIntentActivities( intent, 0 );
int size = list.size();
if (size == 0) {
Toast.makeText(getActivity(), "Can not find image crop app", Toast.LENGTH_SHORT).show();
return;
} else {
intent.setData(mImageCaptureUri);
intent.putExtra("outputX", 200);
intent.putExtra("outputY", 200);
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra("scale", true);
intent.putExtra("return-data", true);
if (size == 1) {
Intent i = new Intent(intent);
ResolveInfo res = list.get(0);
i.setComponent( new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
startActivityForResult(i, CROP_FROM_CAMERA);
} else {
for (ResolveInfo res : list) {
final CropOption co = new CropOption();
co.title = getActivity().getPackageManager().getApplicationLabel(res.activityInfo.applicationInfo);
co.icon = getActivity().getPackageManager().getApplicationIcon(res.activityInfo.applicationInfo);
co.appIntent= new Intent(intent);
co.appIntent.setComponent( new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
cropOptions.add(co);
}
CropOptionAdapter adapter = new CropOptionAdapter(getActivity(), cropOptions);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Choose Crop App");
builder.setAdapter( adapter, new DialogInterface.OnClickListener() {
public void onClick( DialogInterface dialog, int item ) {
startActivityForResult( cropOptions.get(item).appIntent, CROP_FROM_CAMERA);
}
});
builder.setOnCancelListener( new DialogInterface.OnCancelListener() {
#Override
public void onCancel( DialogInterface dialog ) {
if (mImageCaptureUri != null ) {
getActivity().getContentResolver().delete(mImageCaptureUri, null, null );
mImageCaptureUri = null;
}
}
} );
AlertDialog alert = builder.create();
alert.show();
}
}
}
CropOption class:
public class CropOption {
public CharSequence title;
public Drawable icon;
public Intent appIntent;
}
CropOptionAdapter:
public class CropOptionAdapter extends ArrayAdapter<CropOption> {
private ArrayList<CropOption> mOptions;
private LayoutInflater mInflater;
public CropOptionAdapter(Context context, ArrayList<CropOption> options) {
super(context, R.layout.crop_selector, options);
mOptions = options;
mInflater = LayoutInflater.from(context);
}
#Override
public View getView(int position, View convertView, ViewGroup group) {
if (convertView == null)
convertView = mInflater.inflate(R.layout.crop_selector, null);
CropOption item = mOptions.get(position);
if (item != null) {
((ImageView) convertView.findViewById(R.id.iv_icon)).setImageDrawable(item.icon);
((TextView) convertView.findViewById(R.id.tv_name)).setText(item.title);
return convertView;
}
return null;
}
}