How to open gallery intent using Ucrop library in android studio? - java

I am using the library https://github.com/Yalantis/uCrop provided here.
I want to open gallery intent directly when a button is clicked with crop option facility but how do I do it??
Currently, am doing this
public void onclickbutton (View view) {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
if (checkPermissionREAD_EXTERNAL_STORAGE(this)) {
startActivityForResult(intent, GALLERY_INTENT);
}
}
in Onactivity result
if (requestcode == GALLERY_INTENT && resultcode == RESULT_OK)
{
uri = data.getData();
UCrop.of(uri, uri)
.withAspectRatio(16, 9)
.withMaxResultSize(500, 500)
.start(this);
}
Again in onactivity result
if (resultcode == RESULT_OK && requestcode == UCrop.REQUEST_CROP) {
final Uri resultUri = UCrop.getOutput(data);
Toast.makeText(this, resultUri.toString(), Toast.LENGTH_SHORT).show();
} else if (resultcode == UCrop.RESULT_ERROR) {
final Throwable cropError = UCrop.getError(data);
}
Please help me where I am going wrong..

You need to change your Onactivity result
you are passing same uri you must pass source uri and destination uri. like shown below
UCrop.of(sourceUri, destinationUri)
.withAspectRatio(16, 9)
.withMaxResultSize(maxWidth, maxHeight)
.start(context);

Related

How to croping image with source just from camera with Canhub Android Image Cropper with Java

I want to croping image from other activity to another activity with Canhub Android Image Cropper library. This is my code :
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
mCropImageUri = result.getOriginalUri();
createImage();
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
AppLogger.e(result.getError().getMessage());
}
}
if (requestCode == PermissionCheckUtils.LOCATION_PERMISSION_REQUEST_CODE && resultCode == RESULT_OK) {
getLocation();
}
}
and this when i access the camera :
private void openCropImage() {
Intent intent = CropImage.activity().setGuidelines(CropImageView.Guidelines.ON).getIntent(this);
startActivityForResult(intent, CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE);
}
with these code, i open camera but source include galery. My question is how to open the croper with source just from camera. I already read the documentation but I'm confused : https://github.com/CanHub/Android-Image-Cropper
It is very simple !!
In Your openCropImage() Function set following code :
Intent intent = CropImage
.activity()
.setImageSource(includeGallery = false, includeCamera = true)
.setGuidelines(CropImageView.Guidelines.ON)
.getIntent(this);
startActivityForResult(intent, CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE);
That's it !! Happy Coding :-)

Upload your own profile picture

When I start the application, I upload an image using Picasso to imageview. I'm trying to make the user upload their own image. If I take a picture or select it from the gallery, I can display it in an imageview. But I would like to use SharedPreferences to display the image the next time I load the application, which I unfortunately can't do.
Here is my code.
private void showImageOptionDialog(){
final String[] options = getResources().getStringArray(R.array.image_options);
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle(R.string.alert_dialog_title)
.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which){
case 0:
Intent cameraIntent = new Intent();
cameraIntent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, 11);
break;
case 1:
Intent intent = new Intent();
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, 9);
break;
case 2:
SaveSharedPreference.setAvatar(context, "none");
recreate();
break;
}
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//Check if the intent was to pick image, was successful and an image was picked
if(requestCode == 9 && resultCode == RESULT_OK && data != null){
//Get selected image uri from phone gallery
Uri selectedImage = data.getData();
//Display selected photo in image view
//head_image.setImageURI(selectedImage);
assert selectedImage != null;
SaveSharedPreference.setAvatar(context, selectedImage.toString());
}
//Handle camera request
else if(requestCode == 11 && resultCode == RESULT_OK && data != null){
//We need a bitmap variable to store the photo
Bitmap bitmap = (Bitmap) Objects.requireNonNull(data.getExtras()).get("data");
//Display taken picture in image view
head_image.setImageBitmap(bitmap);
}
recreate();
}
Then I try to load using
Picasso.get()
.load(SaveSharedPreference.getAvatar(context))
.placeholder(R.mipmap.ic_launcher)
.transform(new CropCircleTransformation())
.into(head_image);
Thank you for your help
(application runs on Android 7.0+)
It's NOT a good idea to save a photo using SharedPreferences. Try caching it or use a local Database or File system to store and/or restore them

Picture File on RESULT_CANCELED

I want to be able to track image file names when a picture has been taken with the default Camera Glassware. This is so I can delete them when finished. I have the following code:
...
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, TAKE_PICTURE_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == TAKE_PICTURE_REQUEST && resultCode == RESULT_OK) {
String imgPath = data.getStringExtra(Intents.EXTRA_PICTURE_FILE_PATH);
mService.addToImageQueue(imgPath);
}
else if (requestCode == TAKE_PICTURE_REQUEST && resultCode == RESULT_CANCELED) {
...
}
}
If I tap, the resultCode returns RESULT_OK. When I dismiss (swipe down), I get the resultCode RESULT_CANCELED. This is how I intended it to work, except it still generates the image file even if the resultCode is RESULT_CANCELED... I honestly feel like this might be a bug since I tried to use data.getStringExtra(Intents.EXTRA_PICTURE_FILE_PATH); and got a NullPointerException. Am I doing something wrong? Is there a way to get this file name even on RESULT_CANCELED?
You could create a temporary file first (look at the createImageFile() method in this tutorial). If successfully created, do two things:
Save the path of this file to a String.
Include this file's URI in the intent extra (putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile))).
If resultCode is RESULT_CANCELED, you can now trace back to the path of the temporary file and call delete() on it.
Here is some sample code:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_TAKE_PHOTO && resultCode == RESULT_OK) {
Log.v("MainActivity", "Result successful.");
} else if (requestCode == REQUEST_TAKE_PHOTO && resultCode == RESULT_CANCELED) {
Log.v(TAG, "Result canceled. Uri of file is " + mCurrentPhotoPath);
File file = new File(mCurrentPhotoPath);
if (file.exists()) {
Log.v(TAG, "File exists.");
if(file.delete()) {
Log.v(TAG, "File was successfully deleted!");
} else {
Log.v(TAG, "File not successfully deleted.");
}
} else {
Log.v(TAG, "File does not exist!");
}
}
}
Note: For new File(mCurrentPhotoPath) to work, remove "file:" from the beginning of mCurrentPhotoPath.

How can i select an image from gallery and display that in another activity..?

i have created the code to select image from gallery,but i can not pass that value to another activity through bundle..please help me
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
Uri selectedImageUri = data.getData();
selectedImagePath = getPath(selectedImageUri);
System.out.println("Image Path : " + selectedImagePath);
img.setImageURI(selectedImageUri);
enter code here
i need to pass the SelectedImageUri to another activity as bundle
Use this
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
Uri selectedImageUri = data.getData();
selectedImagePath = getPath(selectedImageUri);
System.out.println("Image Path : " + selectedImagePath);
img.setImageURI(selectedImageUri);
Intent intent = new Intent(this , Second_activity.class );
intent.putExtra("image_path", selectedImagePath);
startActivity(intent);
}
it will start the Second Activity, then on the second Activity receive those values by this
Bundle extras = getIntent().getExtras();
if (extras != null) {
String value = extras.getString("image_path");
//use value
}
I know is not exactly what you were looking for but if you pass selectedImagePath using i.putExtra("photoPath", selectedImagePath);, you can later load the image using only the path.
I need to pass the SelectedImageUri to another activity as bundle
=> FYI, Uri class itself implement Parcelable, so you can add and get value into/from Intent directly.
// Add a Uri instance to an Intent
intent.putExtra("SelectedImageUri", SelectedImageUri);
// Get a Uri from an Intent
Uri uri = intent.getParcelableExtra("SelectedImageUri");

onActivityResult returns with data = null

Ok so this here is the intent I am sending
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE); // create a file to save the image
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file name
startActivityForResult(intent, REQUEST_CODE);
And then in the onActivityResult I am doing this:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.i("Intent name:",data.toString());
if (requestCode == REQUEST_CODE){
if (resultCode == Activity.RESULT_OK){
Toast.makeText(this, "Image saved to \n" + fileUri.toString() , Toast.LENGTH_LONG).show();
Toast.makeText(this, "Result Code: " + resultCode , Toast.LENGTH_LONG).show();
//Bitmap mBitMap = BitmapFactory.decodeFile(data.getData().toString());
//imageView.setImageBitmap(mBitMap);
}
else if (resultCode == RESULT_CANCELED){
Toast.makeText(this, "Capture Cancelled", Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(this, "Capture failed", Toast.LENGTH_LONG).show();
}
}
super.onActivityResult(requestCode, resultCode, data);
}
The LogCat is showing a NullPointerException at the line that says Image Saved....
And also this:
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=100, result=-1, data=null}
This happens whether i try to use the data object or the fileUri field of my class.
Why is data being returned null?
Why is it that even though I am using a field of the class i still get the same error?
Whenever you save an image by passing EXTRAOUTPUT with camera intent ie
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
in a file, the data parameter inside the onActivityResult always return null. So, instead of using data to retrieve the image , use the filepath to retrieve the Bitmap.
So onActivityResult would be something like this:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE) {
if (resultCode == Activity.RESULT_OK) {
String[] fileColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(imageUri,
fileColumn, null, null, null);
String contentPath = null;
if (cursor.moveToFirst()) {
contentPath = cursor.getString(cursor
.getColumnIndex(fileColumn[0]));
Bitmap bmp = BitmapFactory.decodeFile(contentPath);
ImageView img = (ImageView) findViewById(R.id.imageView1);
img.setImageBitmap(bmp);
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(this, "Capture Cancelled", Toast.LENGTH_LONG)
.show();
} else {
Toast.makeText(this, "Capture failed", Toast.LENGTH_LONG)
.show();
}
}
super.onActivityResult(requestCode, resultCode, data);
}
Make sure that you have taken imageUri or fileUri as a global variable so that you can access it inside onActivityResult as well. Best of luck
The correct/preferred way to handle data in these cases would be as:
In called Activity set data to the Intent , then setResult code as RESULT_OK and then finish that activity.
In this recieving activity , check the result code.. and retrieve data from Intent variable as :intent.getExtra("... "); //The variables which you have set in the child activity that has been closed now..

Categories

Resources