I have this code to retrieve an image from the gallery
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
intent.putExtra("crop", "true");
intent.putExtra("aspectX", 0);
intent.putExtra("aspectY", 0);
intent.putExtra("outputX", 360);
intent.putExtra("outputY", 360);
try
{
intent.putExtra("return-data", true);
startActivityForResult(Intent.createChooser(intent, "Complete action using"), req_code);
}
catch(ActivityNotFoundException e)
{
// Do nothing for now
}
But even with the intent.putExtra("crop", "true");, after choosing the image, it won't display any crop activity or whatever... Why?
Because it is not supposed to. Just because you put random extras on random Intent objects does not magically force third party apps to do things that they do not do.
Here is the documentation for ACTION_GET_CONTENT. Note that none of the extras that you list there are in the documentation. Hence, no third party app is necessarily going to expect those extras.
Android does not have a built-in image-cropping capability available to developers. There are plenty of image-cropping libraries available, though.
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, SELECT_PHOTO);
try this code :
(For getting image from gallary)
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, GALLERY_REQUEST);
dialog.dismiss();
(After picked image from gallary call this )
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Bitmap bmp = null;
if (resultCode == RESULT_OK) {
try {
if (requestCode == GALLERY_REQUEST) {
// Gallery request result
mImageCaptureUri = data.getData();
TEMP_PHOTO_FILE_NAME = new File(
startCropImage();
} catch (Exception e) {
e.printStackTrace();
File f = new File(getRealPathFromURI(mImageCaptureUri));
if (f.getName().startsWith(FILE_NAME)) {
if (f.exists())
f.delete();
}
}
}
}
private void startCropImage() {
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setType("image/*");
/**
* Check if there is image cropper app installed.
*/
List<ResolveInfo> list = getPackageManager().queryIntentActivities(
intent, 0);
int size = list.size();
/**
* If there is no image cropper app, display warning message
*/
if (size == 0) {
Toast.makeText(this, "Can not find image crop app",
Toast.LENGTH_SHORT).show();
return;
} else {
/**
* Specify the image path, crop dimension and scale
*/
intent.setData(mImageCaptureUri);
intent.putExtra("outputX", 256);
intent.putExtra("outputY", 256);
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra("scale", true);
intent.putExtra("return-data", true);
/**
* There is posibility when more than one image cropper app exist,
* so we have to check for it first. If there is only one app, open
* then app.
*/
if (size == 1) {
Intent i = new Intent(intent);
ResolveInfo res = list.get(0);
i.setComponent(new ComponentName(res.activityInfo.packageName,
res.activityInfo.name));
startActivityForResult(i, CROP_FROM_CAMERA);
}
}
protected void onActivityResult(int requestCode, int resultCode,
Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch (requestCode) {
case SELECT_PHOTO: //Select photo == 1
if (resultCode == RESULT_OK) {
try {
final Uri imageUri = imageReturnedIntent.getData();
Bitmap selectedImage = BitmapFactory
.decodeStream(getContentResolver().openInputStream(
imageUri));
Related
I want to select image from gallery and crop it with 800*600 size, but with sizes larger than 500*500 it is not working!! how can I do it?
my code is as below:
public void showFileChooser() {
Intent imageDownload = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
imageDownload.putExtra("crop", "true");
imageDownload.putExtra("aspectX", 4);
imageDownload.putExtra("aspectY", 3);
imageDownload.putExtra("outputX", 800);
imageDownload.putExtra("outputY", 600);
imageDownload.putExtra("return-data", true);
startActivityForResult(imageDownload, 2);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 2 && resultCode == RESULT_OK && null != data) {
Bundle extras = data.getExtras();
bitmap1 = extras.getParcelable("data");
imageView1.setImageBitmap(bitmap1);
}
}
Try this, it works for me, Hope it'll help you too....
1 - Choose image from gallery
Intent intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*");
startActivityForResult(Intent.createChooser(intent, "Select File"),Util.REQUEST_GALLERY);
2 - Crop image in onActivityResult as below
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == getActivity().RESULT_OK) {
switch (requestCode) {
case Util.REQUEST_GALLERY:
try {
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED) && !Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED_READ_ONLY)) {
File file = new File(Uri.parse(Environment.getExternalStorageDirectory().getAbsolutePath()
+ File.separator+ ".MyImages"+ File.separator+ "picture").getPath());
if (!file.exists()) {
file.mkdirs();
}
selectedPath1 = File.createTempFile("myImages"+ new SimpleDateFormat("ddMMyyHHmmss",Locale.US).format(new Date()),".jpg", file).toString();
croppedImageUri = Uri.fromFile(new File(selectedPath1));
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setDataAndType(data.getData(), "image/*");
intent.putExtra("outputX", 700); // pass width
intent.putExtra("outputY", 700); // pass height
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra("scale", true);
intent.putExtra("noFaceDetection", true);
intent.putExtra("output", croppedImageUri);
startActivityForResult(intent, Util.REQUEST_CROP_IMAGE);
} else {
Toast.show(getActivity(), "Please insert memory card to take pictures and make sure it is writeable");
}
} catch (Exception e) {
e.printStackTrace();
}
break;
case Util.REQUEST_CROP_IMAGE:
Logg.e(getClass().getSimpleName(), "Profile_Pic ===== " + selectedPath1);
imgProfile.setImageURI(Uri.parse("file://" + croppedImageUri));
break;
default:
break;
}
}
}
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);
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 ;-)
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 ;-)
I've an application where user can set his own avatar by taking himself a picture or just picking a picture from the gallery. I've seen in other apps that user, after pick an image its displayed a view where user can "draw" a rectangle selecting which area of the image he wants to use as avatar.
I would like to include this possibility in my app. How can I do that after taking the picture?
Thanks!
Edit:
I'm trying to do it with this but it opens image gallery instead of camera:
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.setType("image/*");
cameraIntent.putExtra("crop", "true");
cameraIntent.putExtra("scale", "true");
cameraIntent.putExtra("outputX", 100);
cameraIntent.putExtra("outputY", 100);
cameraIntent.putExtra("aspectX", 1);
cameraIntent.putExtra("aspectY", 1);
cameraIntent.putExtra("max-width", 30);
cameraIntent.putExtra("max-height", 30);
cameraIntent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(cameraIntent, IMAGEN_CAMARA);
This is how i implemented it in one of my apps that uses this feature. It is quite simple.
private void doTakePhotoAction() {
// http://2009.hfoss.org/Tutorial:Camera_and_Gallery_Demo
// http://stackoverflow.com/questions/1050297/how-to-get-the-url-of-the-captured-image
// http://www.damonkohler.com/2009/02/android-recipes.html
// http://www.firstclown.us/tag/android/
// The one I used to get everything working: http://groups.google.com/group/android-developers/msg/2ab62c12ee99ba30
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//Wysie_Soh: Create path for temp file
mImageCaptureUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(),
"tmp_contact_" + 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) {
//Do nothing for now
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK) {
return;
}
switch (requestCode) {
case CROP_FROM_CAMERA: {
//Wysie_Soh: After a picture is taken, it will go to PICK_FROM_CAMERA, which will then come here
//after the image is cropped.
final Bundle extras = data.getExtras();
if (extras != null) {
Bitmap photo = extras.getParcelable("data");
mPhoto = photo;
mPhotoChanged = true;
mPhotoImageView.setImageBitmap(photo);
setPhotoPresent(true);
}
//Wysie_Soh: Delete the temporary file
File f = new File(mImageCaptureUri.getPath());
if (f.exists()) {
f.delete();
}
InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
mgr.showSoftInput(mPhotoImageView, InputMethodManager.SHOW_IMPLICIT);
break;
}
case PICK_FROM_CAMERA: {
//After an image is taken and saved to the location of mImageCaptureUri, come here
//and load the crop editor, with the necessary parameters (96x96, 1:1 ratio)
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setClassName("com.android.camera", "com.android.camera.CropImage");
intent.setData(mImageCaptureUri);
intent.putExtra("outputX", 96);
intent.putExtra("outputY", 96);
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra("scale", true);
intent.putExtra("return-data", true);
startActivityForResult(intent, CROP_FROM_CAMERA);
break;
}
}
}
Hope it helps :)