Cropping not working in Nexus 5,Device Version 5.1.1 - android

I want to get an image from gallery or camera and then I want to crop it in a particular aspect ratio.
But this code is working in Lollipop Version whereas it works in KitKat.
Can anyone plse helpme to solve this Problem.
public class MainActivity extends Activity {
private static final int PICK_FROM_CAMERA = 1;
private static final int PICK_FROM_GALLERY = 2;
ImageView imgview;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imgview = (ImageView) findViewById(R.id.imageView1);
Button buttonCamera = (Button) findViewById(R.id.btn_take_camera);
Button buttonGallery = (Button) findViewById(R.id.btn_select_gallery);
buttonCamera.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// call android default camera
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI.toString());
// ******** code for crop image
intent.putExtra("crop", "true");
intent.putExtra("aspectX", 2);
intent.putExtra("aspectY", 2);
intent.putExtra("outputX", 150);
intent.putExtra("outputY", 150);
intent.putExtra("return-data", true);
startActivityForResult(intent, PICK_FROM_CAMERA);
}
});
buttonGallery.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//// //TODO Auto-generated method stub
Intent intent = new Intent();
// call android default gallery
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
// ******** code for crop image
intent.putExtra("crop", "true");
intent.putExtra("aspectX", 2);
intent.putExtra("aspectY", 2);
intent.putExtra("outputX", 150);
intent.putExtra("outputY", 150);
try {
intent.putExtra("return-data", true);
startActivityForResult(Intent.createChooser(intent,
"Complete action using"), PICK_FROM_GALLERY);
} catch (ActivityNotFoundException e) {
// Do nothing for now
}
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PICK_FROM_CAMERA) {
Bundle extras = data.getExtras();
Bitmap photo = extras.getParcelable("data");
imgview.setImageBitmap(photo);
}
if (requestCode == PICK_FROM_GALLERY) {
Bundle extras2 = data.getExtras();
if (extras2 != null) {
Bitmap photo = extras2.getParcelable("data");
imgview.setImageBitmap(photo);
}
}
}
}

You must be getting extras2 as null in the last part right?
Same is happening with me! Could you explain what happens precisely? Does it crash the Photos app or you don't see the update in your imageView?

Related

android:select image from gallery then crop that and show in an imageview...but not saving in sharedpreferce

This is the link which is used...android:select image from gallery then crop that and show in an imageview Problem is that images is not saving .When i am selecting picture it is coming in ImageView.but when I came out from this activity as well as from app ,it is not saving...Please help me.
Any help would be appreciated.
public class ImageSelecter extends Activity {
private final int GALLERY_ACTIVITY_CODE=200;
private final int RESULT_CROP = 400;
public ImageView imageView;
// static String picturePath;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView)findViewById(R.id.img_photo);
Button btn_choose = (Button) findViewById(R.id.btn_select_image);
btn_choose.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//Start Activity To Select Image From Gallery
Intent gallery_Intent = new Intent(getApplicationContext(), GalleryUtil.class);
startActivityForResult(gallery_Intent, GALLERY_ACTIVITY_CODE);
// break;
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GALLERY_ACTIVITY_CODE) {
if(resultCode == Activity.RESULT_OK){
GalleryUtil.picturePath = data.getStringExtra("picturePath");
//perform Crop on the Image Selected from Gallery
performCrop(GalleryUtil.picturePath);
}
}
if (requestCode == RESULT_CROP ) {
if(resultCode == Activity.RESULT_OK){
Bundle extras = data.getExtras();
Bitmap selectedBitmap = extras.getParcelable("data");
// Set The Bitmap Data To ImageView
imageView.setImageBitmap(selectedBitmap);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
}
}
}
private void performCrop(String picUri) {
try {
//Start Crop Activity
Intent cropIntent = new Intent("com.android.camera.action.CROP");
// indicate image type and Uri
File f = new File(picUri);
Uri contentUri = Uri.fromFile(f);
cropIntent.setDataAndType(contentUri, "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", 280);
cropIntent.putExtra("outputY", 280);
// retrieve data on return
cropIntent.putExtra("return-data", true);
// start the activity - we handle returning in onActivityResult
startActivityForResult(cropIntent, RESULT_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();
}
}
}
Supporting Class.
public class GalleryUtil extends Activity {
private final static int RESULT_SELECT_IMAGE = 100;
public static final int MEDIA_TYPE_IMAGE = 1;
private static final String TAG = "GalleryUtil";
String mCurrentPhotoPath;
File photoFile = null;
static String picturePath;
SharedPreferences sp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try{
//Pick Image From Gallery
Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_SELECT_IMAGE);
}catch(Exception e){
e.printStackTrace();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode){
case RESULT_SELECT_IMAGE:
if (resultCode == Activity.RESULT_OK && data != null && data.getData() != null) {
try{
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();
//return Image Path to the Main Activity
Intent returnFromGalleryIntent = new Intent();
returnFromGalleryIntent.putExtra("picturePath",picturePath);
setResult(RESULT_OK,returnFromGalleryIntent);
finish();
}catch(Exception e){
e.printStackTrace();
Intent returnFromGalleryIntent = new Intent();
setResult(RESULT_CANCELED, returnFromGalleryIntent);
finish();
}
}else{
Log.i(TAG, "RESULT_CANCELED");
Intent returnFromGalleryIntent = new Intent();
setResult(RESULT_CANCELED, returnFromGalleryIntent);
finish();
}
break;
}
}
}
Share preference cannot save the image, but you can save cropped image as a file, then save the file path to share preference as below.
SharedPreferences.Editor edit = sp.edit();
edit.putString("image_path", impage_path_string);
edit.commit();
Get image from ImageView and convert it to String base64 or if u your saving in database then make field blob
ImageView imageView=(ImageView)findViewById(R.id.profile_image);
Bitmap bitmap = ((BitmapDrawable)imageView.getDrawable()).getBitmap();
ByteArrayOutputStream stream=new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] image=stream.toByteArray();
String userimage= Base64.encodeToString(image, Base64.DEFAULT);
now save image in sharepreferences
SharedPreferences.Editor editor = getSharedPreferences(PREF_LOGIN, MODE_PRIVATE).edit();
editor.putString("USER_IMAGE",userimage);
editor.commit();
now get image from sharepreferences
String image=sharedPreferences.getString("USER_IMAGE", "IMAGE");
byte[] decodedString = Base64.decode(image, Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
imageView.setImageBitmap(decodedByte);
now for
start activity
Intent intent = new Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.INTERNAL_CONTENT_URI);
intent.setType("image/*");
intent.putExtra("crop", "true");
intent.putExtra("scale", true);
intent.putExtra("outputX", 256);
intent.putExtra("outputY", 256);
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra("return-data", true);
startActivityForResult(intent, 1);
now for setimage to image view
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
Toast.makeText(getApplicationContext(),"ddddd",Toast.LENGTH_LONG).show();
final Uri imageUri = data.getData();
final InputStream imageStream = getContentResolver().openInputStream(imageUri);
final Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);
imageUser.setImageBitmap(selectedImage);
} catch (FileNotFoundException e) {
Toast.makeText(getApplicationContext(),e.toString(),Toast.LENGTH_LONG).show();
}

Picking image is not work in LG Optimus

I am developing some Android apps. I want to select picture in gallery and crop it at Fragment. This code is worked at Sony, Samsung, Nexus, AOSP but it doesn't works at LG Optimus phone(ex. Optimus G Pro). It doesn't return when cropping image is done, and it not call onActivityResult callback. Can you help this problem please? The sample code is here.
It's requesting intent code.
getView().findViewById(R.id.info_img).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*");
intent.putExtra("crop", "true");
intent.putExtra("noFaceDetection", true);
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra("scale", true);
intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
startActivityForResult(intent, 0);
}
});
It's onActivityResult Callback. It's Overrided at Fragment Class.
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 0 && resultCode == getActivity().RESULT_OK) {
Bitmap bitmap;
try {
Uri selectedImage = data.getData();
InputStream imageStream = getActivity().getContentResolver().openInputStream(selectedImage);
bitmap = BitmapFactory.decodeStream(imageStream);
} catch (Exception e) {
bitmap = (Bitmap) data.getExtras().get("data");
}
if (bitmap != null){
// TODO : It must Worked at here!!
}
}

How to crop images from camera

How can I crop the camera images. Now it is showing the the image for crop and after selecting the crop section while tap on the "Save" button. Its showing as "saving image". After that nothing is happen. Here is my code.
Button click :
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, MediaStore.Images.Media.EXTERNAL_CONTENT_URI.toString());
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);
startActivityForResult(intent, CAMERA_PIC_REQUEST);
onActivityResult :
Bundle extras = data.getExtras();
Bitmap bitmap = (Bitmap) extras.get("data");
if (bitmap != null) {
Img_View.setImageBitmap(bitmap);
}
You can use this code to perform cropping:
.....
final int CAMERA_CAPTURE = 1;
final int CROP_PIC = 2;
private Uri picUri;
....
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button captureBtn = (Button) findViewById(R.id.capture_btn);
captureBtn.setOnClickListener(this);
}
public void onClick(View v) {
if (v.getId() == R.id.capture_btn) {
try {
// use standard intent to capture an image
Intent captureIntent = new Intent(
MediaStore.ACTION_IMAGE_CAPTURE);
// we will handle the returned data in onActivityResult
startActivityForResult(captureIntent, CAMERA_CAPTURE);
} catch (ActivityNotFoundException anfe) {
Toast toast = Toast.makeText(this, "This device doesn't support the crop action!",
Toast.LENGTH_SHORT);
toast.show();
}
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == CAMERA_CAPTURE) {
// get the Uri for the captured image
picUri = data.getData();
performCrop();
}
// user is returning from cropping the image
else if (requestCode == CROP_PIC) {
// get the returned data
Bundle extras = data.getExtras();
// get the cropped bitmap
Bitmap thePic = extras.getParcelable("data");
ImageView picView = (ImageView) findViewById(R.id.picture);
picView.setImageBitmap(thePic);
}
}
}
/**
* this function does the crop operation.
*/
private void performCrop() {
// take care of exceptions
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(picUri, "image/*");
// set crop properties
cropIntent.putExtra("crop", "true");
// indicate aspect of desired crop
cropIntent.putExtra("aspectX", 2);
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, CROP_PIC);
}
// respond to users whose devices do not support the crop action
catch (ActivityNotFoundException anfe) {
Toast toast = Toast
.makeText(this, "This device doesn't support the crop action!", Toast.LENGTH_SHORT);
toast.show();
}
}
You can use following simple tutorial to perform cropping:
http://khurramitdeveloper.blogspot.in/2013/07/capture-or-select-from-gallery-and-crop.html
http://www.londatiga.net/featured-articles/how-to-select-and-crop-image-on-android/
http://www.coderzheaven.com/2012/12/15/crop-image-android/
http://shaikhhamadali.blogspot.in/2013/09/capture-images-and-crop-images-using.html
Save yourself a lot of time and use this library I was messing around with trying to do it myself and stumbled on this library and its really simple to use and you get a professional looking image cropping view that lets you choose camera or photo library.
Simple example:
Include the library in your gradle
implementation 'com.theartofdev.edmodo:android-image-cropper:2.7.+'
Add permissions to manifest
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
//add this under <application>
<activity android:name="com.theartofdev.edmodo.cropper.CropImageActivity"
android:theme="#style/Base.Theme.AppCompat"/>
In your activity
//on button press or anywhere, this starts the image picking and cropping process
CropImage.activity()
.setGuidelines(CropImageView.Guidelines.ON)
.start(this);
//in your activity where you will get the result of your cropped image
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
Uri resultUri = result.getUri();
//From here you can load the image however you need to, I recommend using the Glide library
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Exception error = result.getError();
}
}
}
Im not affiliated with this software
Try this
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);
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);

crop issue in android : Image aspect ratio is not maintained [duplicate]

I am having a hard time in figuring out how to let the user crop the picture.
I would like to give bitmap variable with loaded bitmap to crop the picture before setting it as wallpaper. But I'm failing to do so... Here is that i tried.
First version. = Works as expected BUT the returned image is in poor resolution. Changing the output to higher value doesn't help. As I saw in some post it is not recommended to use camera as not all devices support this.
Intent intent = new Intent("com.android.camera.action.CROP");
String path = Images.Media.insertImage(context.getContentResolver(), loaded,null, null);
Uri uri = Uri.parse(path);
intent.setData(uri);
intent.putExtra("crop", "true");
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra("outputX", 300);
intent.putExtra("outputY", 300);
intent.putExtra("noFaceDetection", true);
intent.putExtra("return-data", true);
startActivityForResult(intent, 2);
Second. Load up image chooser, and crop afterwards. How can I configurate this to load crop directly on my image? Just like in version 1
Intent photoPickerIntent = new Intent(MediaStore.ACTION_PICK);
photoPickerIntent.setData(uri);
photoPickerIntent.putExtra("crop", "true");
photoPickerIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
photoPickerIntent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
startActivityForResult(photoPickerIntent, 2);
And onActivity result
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK) { return; }
if(requestCode == 2) {
Bundle extras = data.getExtras();
if(extras != null ) {
Bitmap photo = extras.getParcelable("data");
loaded = photo;
}
WallpaperManager myWallpaperManager = WallpaperManager.getInstance(getApplicationContext());
try {
myWallpaperManager.setBitmap(loaded);
} catch (IOException e) {}
}
}
I do not know whever these are the correct methods to make this done, but I hope somebody could point me in the right direction. Which, why, and how to use.
Update: I am still waiting for someone to point out how to do it correctly, answers below are working but returning images in poor resolution, so they are not an option to use
Ok Dear Here I put my Whole code of Crop Image In Android.
This the Global variable.
//This For Image Crop
/**
* Uri for set image crop option .
*/
private Uri mImageCaptureUri;
/**
* int for set key and get key from result activity .
*/
public final int CROP_FROM_CAMERA = 0;
/**
* Bitmap for apply Crop Operation Result.
*/
private Bitmap _tempOpration;
//This is Crop Method.
/**
* Method for apply Crop .
* #param filePath - String path of file .
*/
private void doCrop(String filePath){
try{
//New Flow
mImageCaptureUri = Uri.fromFile(new File(filePath));
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", 300);
intent.putExtra("outputY", 300);
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()
{
public void onCancel( DialogInterface dialog )
{
if (mImageCaptureUri != null )
{
getContentResolver().delete(mImageCaptureUri, null, null );
mImageCaptureUri = null;
}
}
} );
AlertDialog alert = builder.create();
alert.show();
}
}
}
catch (Exception ex)
{
genHelper.showErrorLog("Error in Crop Function-->"+ex.toString());
}
}
This is the another Class witch use for find Crop Activity Intent in Application.
CropOption Class.
public class CropOption
{
public CharSequence title;
public Drawable icon;
public Intent appIntent;
}
this is use For Display List.
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;
}
}
Layout File For CropOptionAdapter
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:gravity="center_vertical">
<ImageView
android:id="#+id/iv_icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:id="#+id/tv_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""/>
</LinearLayout>
This is the resultActivity.witch give the crop image.
/**
* #see android.app.Activity#onActivityResult(int, int, android.content.Intent)
*/
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (resultCode != RESULT_OK) return;
switch (requestCode)
{
case CROP_FROM_CAMERA:
if (data == null)
{
genHelper.showToast("No Crop Activity in This");
return;
}
final Bundle extras = data.getExtras();
if (extras != null)
{
try
{
_tempOpration=extras.getParcelable("data");
imageLayout.setImageBitmap(_tempOpration);
_tempOpration=null;
}
catch (Exception e)
{
e.printStackTrace();
}
}
break;
}
}
//Do This Type It's work on my live app.
genHelper.showToast("No Crop Activity in This");
is my general Class to help display toast message and Error Log.
Bestof Luck.
First, variables:
final int PIC_CROP = 2;
Uri imageUri;
Bitmap thePic;
Before you take a pic from your Camera or your Gallery, put your image into a Uri (imageUri) , use a method called here as "performCrop()" inside try/catch:
private void performCrop(){
try {
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) {
intent.setData(imageUri);
intent.putExtra("crop", "false");
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra("outputX", 256);
intent.putExtra("outputY", 256);
intent.putExtra("scale", 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));
startActivityForResult(i, PIC_CROP);
}
}
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();
}
}
On method onActivityResult:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
if(requestCode == PIC_CROP){
if (resultCode == RESULT_OK) {
Bundle extras = intent.getExtras();
thePic = extras.getParcelable("data");
imageViewPhoto.setImageBitmap(thePic); //in my case, set the image on screen
}else{
//do something
}
}
}
As mentioned in similar threads, Android does not have an official crop intent
(https://commonsware.com/blog/2013/01/23/no-android-does-not-have-crop-intent.html), so I would stay away from using "com.android.camera.action.CROP".
However, in the time since this question was originally posted, Android has added a new API in Kitkat (level 19) that allows users to summon a crop-this-image-and-set-as-wallpaper Activity. See WallpaperManager.getCropAndSetWallpaperIntent(), and this might address your original question.
I also had the problem using the camera and ACTION_PICK that the returned image was very small despite the passed resolution being much larger. I got around this storing the resulted crop image in a temporary file
// temporary storage location, preferably in your cache directory
private final String tempFilePath = "somePath";
// URI instantiated with your temporary storage location
private Uri tempuri = Uri.fromFile(new File(tempFilePath));
// code for startActivityForResult
private final static int ACTIVITY_CROP_IMAGE = 1;
and calling the intent like this
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
photoPickerIntent.setType("image/*");
photoPickerIntent.putExtra("crop", "true");
photoPickerIntent.putExtra("aspectX", wallpaperWidth);
photoPickerIntent.putExtra("aspectY", wallpaperHeight);
photoPickerIntent.putExtra(MediaStore.EXTRA_OUTPUT, tempuri);
photoPickerIntent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
startActivityForResult(photoPickerIntent, ACTIVITY_CROP_IMAGE);
and then in onActivityResult
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (resultCode != RESULT_OK)
return;
if(requestCode == ACTIVITY_CROP_IMAGE)
{
try
{
Bitmap bmp = BitmapFactory.decodeFile(tempFilePath);
if(bmp != null)
{
WallpaperManager myWallpaperManager = WallpaperManager.getInstance(getApplicationContext());
myWallpaperManager.setBitmap(bmp);
}
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
if(tempFilePath != null)
{
File tempFile = new File(tempFilePath);
if(tempFile.exists())
{
tempFile.delete();
}
}
}
}
}
I constructed the above code from the top of my head and didn't actually compile any of it. But the basics are correct and you should get the hang ;-)

Let user crop image

I am having a hard time in figuring out how to let the user crop the picture.
I would like to give bitmap variable with loaded bitmap to crop the picture before setting it as wallpaper. But I'm failing to do so... Here is that i tried.
First version. = Works as expected BUT the returned image is in poor resolution. Changing the output to higher value doesn't help. As I saw in some post it is not recommended to use camera as not all devices support this.
Intent intent = new Intent("com.android.camera.action.CROP");
String path = Images.Media.insertImage(context.getContentResolver(), loaded,null, null);
Uri uri = Uri.parse(path);
intent.setData(uri);
intent.putExtra("crop", "true");
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra("outputX", 300);
intent.putExtra("outputY", 300);
intent.putExtra("noFaceDetection", true);
intent.putExtra("return-data", true);
startActivityForResult(intent, 2);
Second. Load up image chooser, and crop afterwards. How can I configurate this to load crop directly on my image? Just like in version 1
Intent photoPickerIntent = new Intent(MediaStore.ACTION_PICK);
photoPickerIntent.setData(uri);
photoPickerIntent.putExtra("crop", "true");
photoPickerIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
photoPickerIntent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
startActivityForResult(photoPickerIntent, 2);
And onActivity result
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK) { return; }
if(requestCode == 2) {
Bundle extras = data.getExtras();
if(extras != null ) {
Bitmap photo = extras.getParcelable("data");
loaded = photo;
}
WallpaperManager myWallpaperManager = WallpaperManager.getInstance(getApplicationContext());
try {
myWallpaperManager.setBitmap(loaded);
} catch (IOException e) {}
}
}
I do not know whever these are the correct methods to make this done, but I hope somebody could point me in the right direction. Which, why, and how to use.
Update: I am still waiting for someone to point out how to do it correctly, answers below are working but returning images in poor resolution, so they are not an option to use
Ok Dear Here I put my Whole code of Crop Image In Android.
This the Global variable.
//This For Image Crop
/**
* Uri for set image crop option .
*/
private Uri mImageCaptureUri;
/**
* int for set key and get key from result activity .
*/
public final int CROP_FROM_CAMERA = 0;
/**
* Bitmap for apply Crop Operation Result.
*/
private Bitmap _tempOpration;
//This is Crop Method.
/**
* Method for apply Crop .
* #param filePath - String path of file .
*/
private void doCrop(String filePath){
try{
//New Flow
mImageCaptureUri = Uri.fromFile(new File(filePath));
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", 300);
intent.putExtra("outputY", 300);
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()
{
public void onCancel( DialogInterface dialog )
{
if (mImageCaptureUri != null )
{
getContentResolver().delete(mImageCaptureUri, null, null );
mImageCaptureUri = null;
}
}
} );
AlertDialog alert = builder.create();
alert.show();
}
}
}
catch (Exception ex)
{
genHelper.showErrorLog("Error in Crop Function-->"+ex.toString());
}
}
This is the another Class witch use for find Crop Activity Intent in Application.
CropOption Class.
public class CropOption
{
public CharSequence title;
public Drawable icon;
public Intent appIntent;
}
this is use For Display List.
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;
}
}
Layout File For CropOptionAdapter
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:gravity="center_vertical">
<ImageView
android:id="#+id/iv_icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:id="#+id/tv_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""/>
</LinearLayout>
This is the resultActivity.witch give the crop image.
/**
* #see android.app.Activity#onActivityResult(int, int, android.content.Intent)
*/
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (resultCode != RESULT_OK) return;
switch (requestCode)
{
case CROP_FROM_CAMERA:
if (data == null)
{
genHelper.showToast("No Crop Activity in This");
return;
}
final Bundle extras = data.getExtras();
if (extras != null)
{
try
{
_tempOpration=extras.getParcelable("data");
imageLayout.setImageBitmap(_tempOpration);
_tempOpration=null;
}
catch (Exception e)
{
e.printStackTrace();
}
}
break;
}
}
//Do This Type It's work on my live app.
genHelper.showToast("No Crop Activity in This");
is my general Class to help display toast message and Error Log.
Bestof Luck.
First, variables:
final int PIC_CROP = 2;
Uri imageUri;
Bitmap thePic;
Before you take a pic from your Camera or your Gallery, put your image into a Uri (imageUri) , use a method called here as "performCrop()" inside try/catch:
private void performCrop(){
try {
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) {
intent.setData(imageUri);
intent.putExtra("crop", "false");
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra("outputX", 256);
intent.putExtra("outputY", 256);
intent.putExtra("scale", 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));
startActivityForResult(i, PIC_CROP);
}
}
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();
}
}
On method onActivityResult:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
if(requestCode == PIC_CROP){
if (resultCode == RESULT_OK) {
Bundle extras = intent.getExtras();
thePic = extras.getParcelable("data");
imageViewPhoto.setImageBitmap(thePic); //in my case, set the image on screen
}else{
//do something
}
}
}
As mentioned in similar threads, Android does not have an official crop intent
(https://commonsware.com/blog/2013/01/23/no-android-does-not-have-crop-intent.html), so I would stay away from using "com.android.camera.action.CROP".
However, in the time since this question was originally posted, Android has added a new API in Kitkat (level 19) that allows users to summon a crop-this-image-and-set-as-wallpaper Activity. See WallpaperManager.getCropAndSetWallpaperIntent(), and this might address your original question.
I also had the problem using the camera and ACTION_PICK that the returned image was very small despite the passed resolution being much larger. I got around this storing the resulted crop image in a temporary file
// temporary storage location, preferably in your cache directory
private final String tempFilePath = "somePath";
// URI instantiated with your temporary storage location
private Uri tempuri = Uri.fromFile(new File(tempFilePath));
// code for startActivityForResult
private final static int ACTIVITY_CROP_IMAGE = 1;
and calling the intent like this
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
photoPickerIntent.setType("image/*");
photoPickerIntent.putExtra("crop", "true");
photoPickerIntent.putExtra("aspectX", wallpaperWidth);
photoPickerIntent.putExtra("aspectY", wallpaperHeight);
photoPickerIntent.putExtra(MediaStore.EXTRA_OUTPUT, tempuri);
photoPickerIntent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
startActivityForResult(photoPickerIntent, ACTIVITY_CROP_IMAGE);
and then in onActivityResult
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (resultCode != RESULT_OK)
return;
if(requestCode == ACTIVITY_CROP_IMAGE)
{
try
{
Bitmap bmp = BitmapFactory.decodeFile(tempFilePath);
if(bmp != null)
{
WallpaperManager myWallpaperManager = WallpaperManager.getInstance(getApplicationContext());
myWallpaperManager.setBitmap(bmp);
}
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
if(tempFilePath != null)
{
File tempFile = new File(tempFilePath);
if(tempFile.exists())
{
tempFile.delete();
}
}
}
}
}
I constructed the above code from the top of my head and didn't actually compile any of it. But the basics are correct and you should get the hang ;-)

Categories

Resources