Loading a gallery image into an imageview on a dialog - android

I need to load a picture into an imageview that is on a custom dialog (a class that extends dialog).
A dialog is called within a class, extends dialog and let user choose to load a picture from gallery or take a picture from camera...so far so good!
Then startActivityForResult() is not part of Dialog object!
and for getting the result
onActivityResult() also is not part of Dialog class!
Code:
package ....;
.....
public class AnosLeitura extends Dialog {
...
public void btnImageLogo_OnClick(View v) {
edLogo.setImageResource(R.drawable.no_image);
final String[] option = new String[] { "From camera",
"From gallery" };
ArrayAdapter<String> adapter = new ArrayAdapter<String>(context,
android.R.layout.select_dialog_item, option);
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Choice");
builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if (which == 0) { callCamera(); }
if (which == 1) { callGallery(); }
}
});
final AlertDialog dialog = builder.create();
dialog.show();
}
....
public void callGallery() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.putExtra("crop", "true");
intent.putExtra("aspectX", 0);
intent.putExtra("aspectY", 0);
intent.putExtra("outputX", 200);
intent.putExtra("outputY", 150);
intent.putExtra("return-data", true);
//This is not possible!
startActivityForResult(Intent.createChooser(intent, "Complete action using"),
PICK_FROM_GALLERY);
}
// Neither this!
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK)
return;
switch (requestCode) {
case CAMERA_REQUEST:
Bundle extras = data.getExtras();
if (extras != null) {
Bitmap yourImage = extras.getParcelable("data");
ByteArrayOutputStream stream = new ByteArrayOutputStream();
yourImage.compress(Bitmap.CompressFormat.PNG, 100, stream);
imageInByte = stream.toByteArray();
edLogo.setImageBitmap(yourImage);
}
break;
case PICK_FROM_GALLERY:
Bundle extras2 = data.getExtras();
if (extras2 != null) {
Bitmap yourImage = extras2.getParcelable("data");
ByteArrayOutputStream stream = new ByteArrayOutputStream();
yourImage.compress(Bitmap.CompressFormat.PNG, 100, stream);
imageInByte = stream.toByteArray();
edLogo.setImageBitmap(yourImage);
}
break;
}
}
....
}
Does anyone know some solution?
Tks

Related

How to add Image to ImageView dynamically?

I am doing a project in which user can add upto 10 images. When user clicks on "Add new image" button an imageview will be created. I have implemented this in a horizontal scrolling imageview, so that user can scroll horizontally for viewing the images. On clicking on an image, user will be able to add image from camera or gallery. Now the issue is always the image is getting setted on the last imageview even though I clicked on other imageviews. I don't know how to set the image in the selected imageview.
I have referred this (http://sunil-android.blogspot.in/2013/03/insert-imageview-dynamically-using-java.html) link for dynamically creating imageview in horizontal scrollview.
Following is my code:
On clicking on the button imageviews will be added dynamically:
btn_upload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
addImageView(image_layout);
}
});
This is the addImageView function:
private void addImageView(LinearLayout layout) {
imageView = new ImageView(this);
imageView.setImageResource(R.drawable.gallery);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(220, 220);
imageView.setLayoutParams(layoutParams);
imageView.setPadding(0, 0, 10, 0);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
imageView.setId(temp);
layout.addView(imageView);
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
iv_id = v.getId();
showDialog(CONTEXT_MENU_ID);
}
});
}
This is the code for selecting image from camera or gallery :
protected Dialog onCreateDialog(int id) {
if (id == CONTEXT_MENU_ID) {
return iconContextMenu.createMenu();
}
return super.onCreateDialog(id);
}
#SuppressWarnings("deprecation")
#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) {
SelectedImage = extras.getParcelable("data");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
SelectedImage.compress(Bitmap.CompressFormat.JPEG, 100, baos);
imageData = baos.toByteArray();
image = Base64.encodeBytes(imageData);
filename = "img_" + System.currentTimeMillis();
imageView.setImageBitmap(SelectedImage); //setting the image
} else {
image = "";
}
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, "Cannot find image cropping application", 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() {
#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();
}
}
}
take a class variable ImageView
like
ImageView addImage;
change your click method like this
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
iv_id = v.getId();
addImage = (ImageView)v // added code
showDialog(CONTEXT_MENU_ID);
}
});
and finally in onActivityResult replace this line
imageView.setImageBitmap(SelectedImage); //setting the image
with
addImage.setImageBitmap(SelectedImage); //setting the image
hope you will understand the actul problem.

android - ANR on taking picture from gallery/camera

Did someone face the issue when ANR happened after choosing picture from gallery or taking a photo from camera (in my case it returns byte[] array to my app)?
How to solve it?
Upd. Here's the code how an image is picked. But this part of code didn't change and some time ago it worked (some other parts of code were changed, I don't know if it's important).
void chooseOrTakePhotoDialog(OnActivityResultListener listener) {
onActivityResultListener = listener;
final CharSequence[] items = { "Take Photo", "Choose from Library", "Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Add Photo");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (items[item].equals("Take Photo")) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);
} else if (items[item].equals("Choose from Library")) {
Intent intent = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*");
startActivityForResult(
Intent.createChooser(intent, "Select File"),
SELECT_FILE);
} else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
interface OnActivityResultListener {
void onPhotoByteArray(byte[] bytes);
}
private OnActivityResultListener onActivityResultListener;
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.wtf("onActivityResult", "req="+requestCode+" res="+resultCode+" data="+data);
if (resultCode != RESULT_OK) return;
switch (requestCode) {
case REQUEST_CAMERA:
if (onActivityResultListener != null) {
Bitmap bmp = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
onActivityResultListener.onPhotoByteArray(stream.toByteArray());
}
break;
case SELECT_FILE:
Uri uri = data.getData();
try {
byte[] bytes = Helper.readBytes(getContentResolver().openInputStream(uri));
onActivityResultListener.onPhotoByteArray(bytes);
} catch (IOException e) {
e.printStackTrace();
}
break;
}
}
For the case of SELECT_FILE, you can try getting Bitmap like below.
case SELECT_FILE:
if (data != null) {
try {
Uri selectedImage = data.getData();
String[] filePath = {MediaStore.Images.Media.DATA};
Cursor c = getApplicationContext().getContentResolver().query(
selectedImage, filePath, null, null, null);
c.moveToFirst();
int columnIndex = c.getColumnIndex(filePath[0]);
String picturePath = c.getString(columnIndex);
c.close();
Bitmap thumbnail = BitmapFactory.decodeFile(picturePath);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;

how to get filename and path of saved image after cropping

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.

How to crop image using coordinates in android?

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();
}
}
}

Android crop image after taken

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

Categories

Resources