android KitKat image Crop - android

I am passing image url to the following method
private void performCrop(Uri imageUri){
try {
Intent intent = new Intent("com.android.camera.action.CROP");
// intent.setType("image/*");
intent.setDataAndType(imageUri, "image/*");
List<ResolveInfo> list = getActivity().getPackageManager().queryIntentActivities( intent, 0 );
int size = list.size();
if (size >= 0) {
intent.setData(imageUri);
intent.putExtra("crop", "true");
intent.putExtra("aspectX", 0);
intent.putExtra("aspectY", 0);
intent.putExtra("outputX", 150);
intent.putExtra("outputY", 150);
intent.putExtra("scale", true);
intent.putExtra("scaleUpIfNeeded", true);
intent.putExtra("return-data", true);
Intent i = new Intent(intent);
ResolveInfo res = list.get(0);
i.setComponent( new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
System.out.println("before startActivityForResult");
try{
startActivityForResult(i, 2);
}catch(Exception e){
e.printStackTrace();
}
}
}
catch(ActivityNotFoundException anfe){
String errorMessage = "Whoops - your device doesn't support the crop action!";
//Toast toast = Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT);
//toast.show();
}
}
some of images are cropped but some image are not. When I crop image then my app's activity is closed and application starts it's previous or launcher activity so what is the problem??
the main issue is I am not getting any warning or error in log cat, and when I debug it the the till "System.out.println("before startActivityForResult");" the program excutes, that means it does not goes in or calling onActivityResult().
here is onActivityResult method
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if(requestCode ==2 && resultCode == getActivity().RESULT_OK){
System.out.println("inside logic...");
try{
if (data != null) {
// get the returned data
Bundle extras = data.getExtras();
// get the cropped bitmap
Bitmap bmp = extras.getParcelable("data");
imageView.setImageBitmap(bmp);
}
}catch(Exception e){
e.printStackTrace();
}
}
}

this code works successfully for me.try it
private static final int CAMERA_REQUEST = 1;
public static final int MEDIA_TYPE_IMAGE = 1;
final int PIC_CROP = 12;
Button btnCamera;
ImageView iv;
Uri picUri;
static File mediaFile, sendFile;
btnCamera.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
onImgProfile();
}
});
void onImgProfile() {
Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
picUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, picUri);
startActivityForResult(captureIntent, CAMERA_REQUEST);
}
private Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
}
private File getOutputMediaFile(int type) {
File mediaStorageDir = new File(
Environment.getExternalStorageDirectory(), "MyCameraApp");
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d("MyCameraApp", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
.format(new Date());
if (type == MEDIA_TYPE_IMAGE) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".jpg");
} else {
return null;
}
return mediaFile;
}
#SuppressWarnings("unchecked")
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_REQUEST) {
// if (Build.VERSION.SDK_INT < 19) {
try {
if (mediaFile.exists()) {
performCrop();
// new SavePhotoData().execute();
}
} catch (Exception e) {
// TODO: handle exception
}
// }
} else if (requestCode == 11) {
try {
picUri = data.getData();
Log.i("uri", "" + picUri);
performCrop();
} catch (Exception e) {
// TODO: handle exception
}
} else if (requestCode == PIC_CROP) {
// get the returned data
try {
Bundle extras = data.getExtras();
// get the cropped bitmap
Bitmap thePic = extras.getParcelable("data");
// retrieve a reference to the ImageView
// display the returned cropped image
iv.setImageBitmap(thePic);
File mediaStorageDir = new File(
Environment.getExternalStorageDirectory(),
"MyCameraApp");
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d("MyCameraApp", "failed to create directory");
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
.format(new Date());
sendFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".png");
FileOutputStream fOut = new FileOutputStream(sendFile);
thePic.compress(Bitmap.CompressFormat.PNG, 85, fOut);
fOut.flush();
fOut.close();
} catch (Exception e) {
e.printStackTrace();
}
}
if (resultCode == 3) {
Bundle b = data.getExtras();
b.getString("msg");
}
};
private void performCrop() {
// take care of exceptions
try {
// call the standard crop action intent (the user device may not
// support it)
try {
Intent cropIntent = new Intent("com.android.camera.action.CROP");
// indicate image type and Uri
cropIntent.setDataAndType(picUri, "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 (Exception e) {
// TODO: handle exception
}
}
// respond to users whose devices do not support the crop action
catch (ActivityNotFoundException anfe) {
// display an error message
String errorMessage = "Whoops - your device doesn't support the crop action!";
Toast toast = Toast.makeText(getApplicationContext(), errorMessage,
Toast.LENGTH_SHORT);
toast.show();
}
}
this code works for not only kitkat but all cersion of android

Android all devices does not have a cropping intent according #CommonsWare http://commonsware.com/blog/2013/01/23/no-android-does-not-have-crop-intent.html
so better is to use libraries
some of them are:
https://github.com/jdamcd/android-crop
https://github.com/IsseiAoki/SimpleCropView
https://android-arsenal.com/details/1/3054

Related

How to use Camera Intent with Crop Intent both at one Intent in Webview

I followed this to use camera from web-view..with upload,,,
So in that I am getting Default camera.. and I am capturing.. and Uploading...
So I want to Crop them...and Upload.. with Max 2 Megapixel resolution not more than 2Mp...
I followed this to use Crop...
I it Possible to use both intents together in web-view... and resolution should be low..
I mean after capture it should show crop... option... and then upload,,,
Can any one suggest me...
private void pickImage() {
AlertDialog.Builder builder = new AlertDialog.Builder(Create_event.this);
builder.setTitle("Choose Image");
builder.setMessage("Select Image");
builder.setPositiveButton("Gallery",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent photoPickerIntent = new Intent(
Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, 1);
dialog.dismiss();
}
});
builder.setNegativeButton("Camera",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent cameraIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, 2);
dialog.dismiss();
}
});
builder.show();
}
private Uri getTempUri() {
return Uri.fromFile(getTempFile());
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == 2 || requestCode == 1) {
try {
Intent cropIntent = new Intent(
"com.android.camera.action.CROP");
// indicate image type and Uri
cropIntent.setDataAndType(data.getData(), "image/*");
cropIntent.putExtra(MediaStore.EXTRA_OUTPUT, getTempUri());
cropIntent.putExtra("outputFormat",
Bitmap.CompressFormat.JPEG.toString());
// 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, 3);
} catch (ActivityNotFoundException anfe) {
// display an error message
String errorMessage = "Whoops - your device doesn't support the crop action!";
Toast toast = Toast.makeText(this, errorMessage,
Toast.LENGTH_SHORT);
toast.show();
}
} else if (requestCode == 3) {
try {
Log.e("testing", "return data is " + data.getData());
String filePath = Environment.getExternalStorageDirectory()
+ "/" + TEMP_PHOTO_FILE;
System.out.println("path " + filePath);
uImage = BitmapFactory.decodeFile(filePath);
ByteArrayOutputStream bao = new ByteArrayOutputStream();
uImage.compress(Bitmap.CompressFormat.PNG, 100, bao);
ba = bao.toByteArray();
ivcreateeventflyer.setImageBitmap(uImage);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
private static final String TEMP_PHOTO_FILE = "temporary_holder.jpg";
private File getTempFile() {
if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
File file = new File(Environment.getExternalStorageDirectory(),
TEMP_PHOTO_FILE);
try {
file.createNewFile();
} catch (IOException e) {
}
return file;
} else {
return null;
}
}
Use this code to take pic from camera or gallery with crop functionality. hope it may be help you

Android chat application emoji's issue

I am working on Android chat application. Now I want to send emoji's in my chat module. How can i implement emoji' in chat application? Please guide me for this app. If there is any API for this app then also suggest me. Thanks
public void callAsynchronousTask() {
final Handler handler = new Handler();
timer = new Timer();
TimerTask doAsynchronousTask = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
try {
new GetSingleChat(Chat_Detail_Single.this).execute(friend_id);
} catch (NullPointerException e) {
}
}
});
}
};
timer.schedule(doAsynchronousTask, 1000, 1000);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btncamera:
Dialog_Manager.chooseImage(Chat_Detail_Single.this, "singlechat");
break;
case R.id.img_back:
timer.cancel();
finish();
break;
case R.id.btnsend:
String message_ = edt_mes.getText().toString();
if (message_.replace(" ", "").length() == 0) {
} else {
edt_mes.setText("");
new Send_chat_message(Chat_Detail_Single.this).execute(SharedPref.getUserID(this), friend_id, "mes", message_);
}
break;
}
}
public static void get_chat_data(List<Chat_prop> fetch_chat) {
MyCustomList.clear();
MyCustomList.addAll(fetch_chat);
try {
if (adptor == null) {
adptor = new Single_Chat_Adap(activity,
MyCustomList);
Chat_Detail_Single.listView.setAdapter(adptor);
Chat_Detail_Single.listView.setSelection(MyCustomList
.size() - 1);
lastCount = MyCustomList.size();
} else {
if (lastCount != MyCustomList.size()) {
lastCount = MyCustomList.size();
adptor.notifyDataSetChanged();
Chat_Detail_Single.listView
.setSelection(MyCustomList.size());
}
}
} catch (NullPointerException e) {
} catch (Exception e) {
// TODO: handle exception
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
if (requestCode == Dialog_Manager.Gallery_Intent
&& resultCode == RESULT_OK && data != null) {
File direct = new File(
Environment.getExternalStorageDirectory() + "/Fun You");
if (!direct.exists()) {
if (direct.mkdir())
;
}
long time = System.currentTimeMillis();
capturepath1 = direct.getAbsolutePath() + "/" + time + ".jpg";
File file = new File(capturepath1);
Uri outputFileUri = Uri.fromFile(file);
Uri selectedImage = data.getData();
imagePath = getPath(selectedImage);
Intent cropIntent = new Intent("com.android.camera.action.CROP");
Uri contentUri = selectedImage;
cropIntent.setDataAndType(contentUri, "image/*");
cropIntent.putExtra("crop", "true");
cropIntent.putExtra("aspectX", 1);
cropIntent.putExtra("aspectY", 1);
cropIntent.putExtra("outputX", 1000);
cropIntent.putExtra("outputY", 1000);
cropIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
cropIntent.putExtra("return-data", true);
startActivityForResult(cropIntent, 3);
} else if (requestCode == Dialog_Manager.Camera_Intent
&& resultCode == RESULT_OK) {
File direct = new File(
Environment.getExternalStorageDirectory() + "/Fun You");
if (!direct.exists()) {
if (direct.mkdir())
;
}
long time = System.currentTimeMillis();
capturepath1 = direct.getAbsolutePath() + "/" + time + ".jpg";
File file = new File(capturepath1);
Uri outputFileUri = Uri.fromFile(file);
File photos = new File(imagePath);
Uri selectedImage = Uri.fromFile(photos);
Intent cropIntent = new Intent("com.android.camera.action.CROP");
Uri contentUri = selectedImage;
cropIntent.setDataAndType(contentUri, "image/*");
cropIntent.putExtra("crop", "true");
cropIntent.putExtra("aspectX", 1);
cropIntent.putExtra("aspectY", 1);
cropIntent.putExtra("outputX", 1000);
cropIntent.putExtra("outputY", 1000);
cropIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
cropIntent.putExtra("return-data", true);
startActivityForResult(cropIntent, 3);
} else if (requestCode == 3) {
try {
Bitmap thumbnail = null;
Bundle extras = data.getExtras();
if (extras != null) {
thumbnail = extras.getParcelable("data");
Bitmap bm = thumbnail;
bm = ExtraMethods.decodeFile(capturepath1);
bm = ExifUtils.rotateBitmap(capturepath1, bm);
// new Uplaod_image().execute(capturepath1);
new Send_chat_message(Chat_Detail_Single.this).execute(SharedPref.getUserID(this), friend_id, "image", capturepath1);
}
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(), e + "", Toast.LENGTH_LONG)
.show();
}
}
public String getPath(Uri uri) {
if (uri == null) {
return null;
}
String[] projection = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(uri, projection, null, null,
null);
if (cursor != null) {
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
return uri.getPath();
}
There is no specific api available to implement and send emojis. You can achieve this using ImageSpan objects. The TextViews and EditTexts use Spanned/Spannable objects to store the entered text content, not just mere Java Strings. On these Spanned/Spannable objects you can define spans for sections on the text that modifies the way that those sections are shown. So you can display images in place of certain sections.
Check the docs:
Also, I found a blog, it might be helpful for you.
This Library is all you need to implement Emojicons. Just don't forget to change your TextViews and EditTexts to this Library's EmojiconTextViews and EmojiconEditTexts respectively.
Hope this helps.
You need to encode emoji before upload.
in this way you encode emoji to UTF code
try {
String mystring = URLEncoder.encode(strComments, HTTP.UTF_8);
param.add(new BasicNameValuePair("comment", mystring));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
for decoding
enter code here
try {
String Title = URLDecoder.decode(comment, "UTF-8");
holder.tvComment.setText(Title);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}

Camera Activity not returns path of image

I have task to capture image from camera and send that image to crop Intent. following is the code i have written
for camera capture
Intent captureIntent = new Intent(
MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(captureIntent, CAMERA_CAPTURE);
In on Activity result
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == CAMERA_CAPTURE) {
// get the Uri for the captured image
picUri = data.getData(); // picUri is global string variable
performCrop();
}
}
}
public void performCrop() {
try {
Intent cropIntent = new Intent("com.android.camera.action.CROP");
cropIntent.setDataAndType(picUri, "image/*");
cropIntent.putExtra("crop", "true");
cropIntent.putExtra("aspectX", 3);
cropIntent.putExtra("aspectY", 2);
cropIntent.putExtra("outputX", 256);
cropIntent.putExtra("outputY", 256);
cropIntent.putExtra("return-data", true);
startActivityForResult(cropIntent, CROP_PIC);
} catch (ActivityNotFoundException anfe) {
String errorMessage = "Your device doesn't support the crop action";
Toast toast = Toast.makeText(getApplicationContext(), errorMessage,
Toast.LENGTH_SHORT);
toast.show();
}
}
I am getting different behaviours on different devices
In some devices i am getting error "couldn't find item".
In some devices after capturing image activity stuck and doesn't go ahead
I have also tried this
Please tell me the Right way to do this
You can by calling the intent like below:
int REQUEST_IMAGE_CAPTURE = 1;
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(android.os.Environment.getExternalStorageDirectory(), "temp.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
((Activity) context).startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);
And in your activity inside OnActivityResult you get the path like this:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == REQUEST_IMAGE_CAPTURE) {
File f = new File(Environment.getExternalStorageDirectory().toString());
for (File temp : f.listFiles()) {
if (temp.getName().equals("temp.jpg")) {
f = temp;
break;
}
}
try {
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
Bitmap bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(),
bitmapOptions);
Matrix matrix = new Matrix();
matrix.postRotate(-90);
Bitmap rotatedBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
rotatedBitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
byte[] attachmentBytes = byteArrayOutputStream.toByteArray();
String attachmentData = Base64.encodeToString(attachmentBytes, Base64.DEFAULT);
String path = android.os.Environment
.getExternalStorageDirectory()
+ File.separator
+ "CTSTemp" + File.separator + "default";
f.delete();
ESLogging.debug("Bytes size = " + attachmentBytes.length);
ESLogging.debug("FilePath = " + path);
OutputStream outFile = null;
File file = new File(path, String.valueOf(System.currentTimeMillis()) + ".jpg");
try {
outFile = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outFile);
outFile.flush();
outFile.close();
} catch (FileNotFoundException e) {
ESLogging.error("FileNotFoundException while uploading new attachment in class HomeActivity", e);
e.printStackTrace();
} catch (IOException e) {
ESLogging.error("IOException while uploading new attachment in class HomeActivity", e);
e.printStackTrace();
} catch (Exception e) {
ESLogging.error("Exception while uploading new attachment in class HomeActivity", e);
e.printStackTrace();
}
} catch (Exception e) {
ESLogging.error("Exception while uploading new attachment in class HomeActivity", e);
e.printStackTrace();
}
}
}
}
//Declare this in class
private static int RESULT_LOAD_IMAGE = 1;
String picturePath="";
// write in button click event
Intent i = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
//copy this code in after onCreate()
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK
&& null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
picturePath = cursor.getString(columnIndex);
cursor.close();
ImageView imageView = (ImageView) findViewById(R.id.img); //place imageview in your xml file
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
}
write the following permission in manifest file
1.read external storage
2.write external storage
try this tutorial http://www.androidhive.info/2013/09/android-working-with-camera-api/ this will help you

Crop Images issues with Capture Image using Android

I am using Camera Function to Capture Images 2 times from different buttons. After Captured Image, It goes to Crop Option where user can crop the Image. It is also working fine.
But, now issue is that when user capture second image then App redirects to Crop image and show first image only rather than second capture image. I am also deleting image after It has been set to ImageView. Don't know what is the wrong ?
Please Help me to solve this issue.
My Code :
Bitmap bm_PhotoProof = null;
Bitmap bm_AddressProof = null;
private static final String TEMP_PHOTO_FILE = "tmp_ihis.jpg";
private static final int REQ_CODE_PICK_IMAGE_PHOTOPROOF = 0;
private static final int REQ_CODE_PICK_IMAGE_ADDRESSPROOF = 1;
imgPhotoProof.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent cameraIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, getTempUri());
cameraIntent.putExtra("outputFormat",
Bitmap.CompressFormat.JPEG.toString());
startActivityForResult(cameraIntent,
REQ_CODE_PICK_IMAGE_PHOTOPROOF);
}
});
imgAddressProof.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent cameraIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, getTempUri());
cameraIntent.putExtra("outputFormat",
Bitmap.CompressFormat.JPEG.toString());
startActivityForResult(cameraIntent,
REQ_CODE_PICK_IMAGE_ADDRESSPROOF);
}
});
private Uri getTempUri() {
return Uri.fromFile(getTempFile());
}
private File getTempFile() {
File f = new File(Environment.getExternalStorageDirectory(),
TEMP_PHOTO_FILE);
try {
f.createNewFile();
} catch (IOException e) {
Log.e("getTempFile()->", e.getMessage().toString());
}
return f;
}
public void cropCapturedImage(Uri picUri, String Type) {
Intent cropIntent = new Intent("com.android.camera.action.CROP");
cropIntent.setDataAndType(picUri, "image/*");
cropIntent.putExtra("crop", "true");
cropIntent.putExtra("aspectX", 0);
cropIntent.putExtra("aspectY", 0);
cropIntent.putExtra("outputX", 256);
cropIntent.putExtra("outputY", 256);
cropIntent.putExtra("return-data", true);
if (Type.equals("Photo")) {
startActivityForResult(cropIntent, 5);
} else {
startActivityForResult(cropIntent, 6);
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == REQ_CODE_PICK_IMAGE_PHOTOPROOF) {
File tempFile = getTempFile();
cropCapturedImage(Uri.fromFile(tempFile), "Photo");
} else if (requestCode == REQ_CODE_PICK_IMAGE_ADDRESSPROOF) {
File tempFile = getTempFile();
cropCapturedImage(Uri.fromFile(tempFile), "Address");
}
if (resultCode != Activity.RESULT_CANCELED) {
if (requestCode == 5) {
if (data != null) {
Bundle extras = data.getExtras();
bm_PhotoProof = extras.getParcelable("data");
}
imgPhotoProof_Pic.setImageBitmap(bm_PhotoProof);
File tempFile = getTempFile();
if (tempFile.exists()) {
tempFile.delete();
}
}
if (requestCode == 6) {
if (data != null) {
Bundle extras = data.getExtras();
bm_AddressProof = extras.getParcelable("data");
}
imgAddressProof_Pic.setImageBitmap(bm_AddressProof);
File tempFile = getTempFile();
if (tempFile.exists()) {
tempFile.delete();
}
}
}
}
}
I have solved this issue.Before, i was deleting just file. Now, I have also cleared cached and it solved my problem.
File tempFile = getTempFile();
if (tempFile.exists()) {
tempFile.delete();
}
to
File tempFile = getTempFile();
File cacheDir = getActivity().getCacheDir();
File file = new File(cacheDir, getTempFile().toString());
file.delete();

Android Tablet cannot return to intent after cropping

Hi I have this app where I allow user to take image and crop. It works on my phones but not on my Samsung Galaxy Tablet. The "Saving image" dialog just remain and not return to my app's onActivityResult... It does return if I cancel crop[
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == 1337 && resultCode == -1) {
File fi = new File("/sdcard/tmp");
// get the Uri for the captured image - NEW
try {
mImageCaptureUri = Uri
.parse(android.provider.MediaStore.Images.Media
.insertImage(getContentResolver(),
fi.getAbsolutePath(), null, null));
// Log.i("",String.valueOf(thumbnail.getHeight()));
} catch (Exception ex) {
String errorMessage = "Your device doesn't support the crop action!";
Toast toast = Toast.makeText(this, errorMessage,
Toast.LENGTH_SHORT);
toast.show();
}
performCrop();
}
if (requestCode == PIC_CROP) {
try {
final TextView imgTv = (TextView) findViewById(R.id.info);
// Bundle extras = data.getExtras();
// thumbnail = extras.getParcelable("data");
Log.i("a", "test");
// NEW
final String filePath = Environment.getExternalStorageDirectory()
+ "/temporary_holder.jpg";
thumbnail = BitmapFactory.decodeFile(filePath);
ImageView image = (ImageView) findViewById(R.id.img);
image.setImageBitmap(thumbnail);
}}
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");
// indicate image type and Uri
cropIntent.setDataAndType(mImageCaptureUri, "image/*");
// set crop properties
cropIntent.putExtra("crop", "true");
// indicate aspect of desired crop
cropIntent.putExtra("aspectX", 4);
cropIntent.putExtra("aspectY", 3);
// indicate output X and Y
cropIntent.putExtra("outputX", 500);
cropIntent.putExtra("outputY", 300);
// retrieve data on return
// cropIntent.putExtra("return-data", true);
File f = new File(Environment.getExternalStorageDirectory(),
"/temporary_holder.jpg");
try {
f.createNewFile();
} catch (IOException ex) {
Log.e("io", ex.getMessage());
}
uri = Uri.fromFile(f);
cropIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
startActivityForResult(cropIntent, PIC_CROP);
} // respond to users whose devices do not support the crop action
catch (ActivityNotFoundException anfe) {
// display an error message
String errorMessage = "Your device doesn't support the crop action!";
Toast toast = Toast
.makeText(this, errorMessage, Toast.LENGTH_SHORT);
toast.show();
}
}
Please refer following links for better solution:
Link 1
Link 2

Categories

Resources