I have 3 tasks:
Pick image from gallery
Capture image from camera
Crop image from 1 or 2.
The quality of image must be good.
Are there any solution for my problem? May be some libraries?
Android, by default, actually has all those you enumerated.
To pick an image from gallery
Intent pickPhoto = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(pickPhoto, FROM_GALLERY);
To capture image from camera
Intent takePicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(takePicture, FROM_CAMERA);
To fetch the results of the intents above and the do the cropping
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case FROM_GALLERY:
case FROM_CAMERA: {
if (resultCode == Activity.RESULT_OK) {
Uri selectedImage = data.getData();
Intent cropIntent = new Intent("com.android.camera.action.CROP");
cropIntent.setDataAndType(selectedImage, "image/*");
cropIntent.putExtra("crop", "true");
cropIntent.putExtra("aspectX", 1);
cropIntent.putExtra("aspectY", 1);
cropIntent.putExtra("outputX", MAX_WIDTH);
cropIntent.putExtra("outputY", MAX_HEIGHT);
cropIntent.putExtra("return-data", true);
startActivityForResult(cropIntent, PICTURE_CROP);
}
break;
}
case PICTURE_CROP: {
if (resultCode == Activity.RESULT_OK) {
final Bundle extras = data.getExtras();
if (extras != null) {
Bitmap photo = extras.getParcelable("data");
// Hurray! You now have the photo as a Bitmap
}
}
break;
}
}
}
Update:
According to this post you should not use com.android.camera.action.CROP since this does not exist in all devices. In that post, he also enumerated alternatives which I will also list here:
https://github.com/lvillani/android-cropimage
https://github.com/biokys/cropimage
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 want crop photo that i take from camera, so far i try do it like this but with no success
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));
intent.putExtra("crop", "true");
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra("outputX", 200);
intent.putExtra("outputY", 200);
getActivity().startActivityForResult(intent, REQUEST_CAMERA);
is it possible to do it without any 3th part libraries.?
i checked https://github.com/biokys/cropimage
but it doesnt gave me any results
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
String path = data.getStringExtra(CropImage.IMAGE_PATH);
// if nothing received
if (path == null) {
return;
}
// cropped bitmap
Bitmap bitmap = BitmapFactory.decodeFile(path);
((ImageView) findViewById(R.id.userpicture)).setImageBitmap(bitmap);
}
is it possible to do it without any 3th part libraries.?
Not reliably. Android does not have a CROP Intent.
i checked https://github.com/biokys/cropimage but it doesnt gave me any results
Perhaps you did not integrate it properly. In addition to the libraries mentioned in my blog post (linked to above), the Android Arsenal has a few options.
try this
private void performCrop(Uri picUri) {
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", 128);
cropIntent.putExtra("outputY", 128);
// retrieve data on return
cropIntent.putExtra("return-data", true);
// start the activity - we handle returning in onActivityResult
startActivityForResult(cropIntent, PIC_CROP);
}
// 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(getActivity(), errorMessage, Toast.LENGTH_SHORT);
toast.show();
}
}
declare:
final int PIC_CROP = 1;
at top.
In onActivity result method, writ following code:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PIC_CROP) {
if (data != null) {
// get the returned data
Bundle extras = data.getExtras();
// get the cropped bitmap
Bitmap selectedBitmap = extras.getParcelable("data");
imgView.setImageBitmap(selectedBitmap);
}
}
}
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));
*I am working on an application in which i have to take image,crop it and then proceed to further implementation.When i capture image and save it to sdcard it's quality is good but when i try to save image after cropping,It's quality is worst.
Below is my code
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if (arg0.getId() == R.id.captureimage) {
try {
//use standard intent to capture an image
final Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAMERA_CAPTURE);
}
catch(Exception e){ String errorMessage = "your device doesn't support capturing images!";
Toast toast = Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT);
toast.show();}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_CAPTURE) {
Uri picUri = data.getData();
performCrop(picUri);
}
else if(requestCode == PIC_CROP){this.finish();
Intent i=new Intent(getApplicationContext(),display.class);
i.putExtra("jao", "jao");
startActivity(i);}
else {
Log.v("", "User cancelled");
}
}private void performCrop(Uri picUri) {
// TODO Auto-generated method stub
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);
File file = new File(_path);
Uri outputFileUri = Uri.fromFile(file);
cropIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
//retrieve data on return
cropIntent.putExtra("return-data", true);
//start the activity - we handle returning in onActivityResult
startActivityForResult(cropIntent, PIC_CROP);
}
Please guide me how can i make my cropped image quality better because with bad quality image i cannot do my other tasks....