How to crop images from gallery and camera - android

i know there is alot of diffrent tutorials online to teach u how to implement cropping, but im having trouble applying cropping function to my project. im building an OCR application, i used the onActivityresult to perform my OCR. i do not know how to add the cropping function into my code. Please help.
This is my button to press for gallery.
findViewById(R.id.b1).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, REQUEST_GALLERY);
}
});
And this is my camera button.
findViewById(R.id.imageButton).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String filename = System.currentTimeMillis() + ".jpg";
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, filename);
values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
imageUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Intent intent = new Intent();
intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent, REQUEST_CAMERA);
}
});
This is my onActivityresult
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQUEST_GALLERY:
if (resultCode == RESULT_OK) {
inspect(data.getData());
}
break;
case REQUEST_CAMERA:
if (resultCode == RESULT_OK) {
if (imageUri != null) {
inspect(imageUri);
}
}
break;
default:
super.onActivityResult(requestCode, resultCode, data);
break;
}
}
because im passing my image into "inspect" class, how do i implement the cropping before passing them into inspect ?

You should not do much work in activity result, you can start a new thread to do complicated things and it's easy to do this using rxjava. Do this in you case:
Observable.just(imgUri)
.subscribeOn(Schedulers.io())
.map(uri -> MediaStore.Images.Media.getBitmap(getContentResolver(), uri))
.map(bitmap -> getCroppedImgAndReturnItsUri(bitmap))
.observeOn(AndroidSchedulers.mainThread())
.subscribe(uri -> {inspect(uri);}, throwable -> {})
And don't forget to dispose this disposable on your activity stop.

Related

Activity recreating before getting a resultant url after capturing a picture In redmi Note 4

I have one activity and multiple fragments.Here my use case is I have to capture an image using from one of the fragment,the resultant image will shown in an ImageView in that fragment.But here the problem is the fragment destroying its view and activity was recreating again.How can I show the resultant image in that fragment ? This problem occuring only in RedmiNote4.Thanks in advance.
Here is my code
cameraBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//check permissions
if(hasPermission){
values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, "Image File name");
mCapturedImageURI =getActivity().getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Intent intentPicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intentPicture.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);
intentPicture.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
if(intentPicture.resolveActivity(getActivity().getApplicationContext().getPackageManager()) != null) {
startActivityForResult(intentPicture,CAMERA_REQUEST);
}
}
}
});
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_CANCELED) {
return;
} else if(requestCode == CAMERA_REQUEST ){
Uri uri =mCapturedImageURI;
//setImage
loadImage(uri)
}
}
I am also RedmiNote4 user.
With this case I was facing that issue.
When I turn off flag "Don't keep activities" It solved my issue after digging solution for 2 days.

Issue with Fragment it doesn't support Activity Result

//As per some suggestions I write this code in my project but still going to face same issue
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == PICK_IMAGE/PICK_Camera_IMAGE && resultCode == Activity.RESULT_OK)
{
Fragment yourFragment = getSupportFragmentManager().findFragmentById(R.id.frame_container); // same tag while adding fragment for the first time.
if (yourFragment != null)
{
yourFragment.onActivityResult(requestCode, resultCode, data); //calling method that should be defined in your fragment.
}
}
}
//this code is from MainActivity.java class..
//Should I write Above Activity Result Code into my Mainfragment class?
gallery.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try {
Intent gintent = new Intent();
gintent.setType("image/*");
gintent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(
gintent, "Select Picture"), PICK_IMAGE);
} catch (Exception e) {
Toast.makeText(mainActivity,
e.getMessage(), Toast.LENGTH_LONG).show();
Log.e(e.getClass().getName(), e.getMessage(), e);
}
d.dismiss();
}
});
camera.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// define the file-name to save photo taken by Camera
// activity
String fileName = "new-photo-name.jpg";
// create parameters for Intent with filename
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, fileName);
values.put(MediaStore.Images.Media.DESCRIPTION,
"Image captured by camera");
// imageUri is the current activity attribute, define
// and save it for later usage (also in
// onSaveInstanceState)
imageUri = getActivity().getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
values);
// create new Intent
Intent intent = new Intent(
MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
startActivityForResult(intent, PICK_Camera_IMAGE);
}
});
// This is the code belongs to my Profile Fragment class..
// I stuck over here didn't get any kind of solution
// I'm using fragment viewpager
Here you done mistake if do like this
**PICK_IMAGE/PICK_Camera_IMAGE**
it will divide your request codes and resulting code will be different
if(requestCode == PICK_IMAGE/PICK_Camera_IMAGE && resultCode ==Activity.RESULT_OK)
{
//...
}
Use this code instead of older
if(requestCode == PICK_IMAGE && resultCode == Activity.RESULT_OK)
{
//...
}else if(requestCode == PICK_Camera_IMAGE && resultCode ==Activity.RESULT_OK)
{
//...
}
To get the result in your fragment make sure you call
startActivityForResult(intent, PICK_Camera_IMAGE);
instead of
getActivity().startActivityForResult(intent, PICK_Camera_IMAGE);
inside your fragment.
As all fragments are invoked into an activity so the result will have to be transferred into the fragments from onActivityResult of your activity just like you are doing.
You will have to create you own onActivityResult method in your fragment with same signature as well to update your fragment UI.
remove this
super.onActivityResult(requestCode, resultCode, data);

How can I get the URI with a custom camera in Android?

I'm switching from using the default camera to finally growing a pair and deciding to make a custom camera. It's only showing me how much I don't fully understand.
Here is basically way I have been doing things in the main activity as far as photos go, but it will no longer work:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
uiHelper.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == PICK_PHOTO_REQUEST) {
if (data == null) {
Toast.makeText(this, "General Error!", Toast.LENGTH_LONG).show();
}
else {
mMediaUri = data.getData();
}
Log.i(TAG, "Media URI: " + mMediaUri);
}
else {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
mediaScanIntent.setData(mMediaUri);
sendBroadcast(mediaScanIntent);
}
(...)
Here is the picture saving function along with a couple others of the new camera:
(...)
#Override
public void onPictureTaken(byte[] data, Camera camera) {
Log.d("Picture taken");
String path = savePictureToFileSystem(data);
setResult(path);
finish();
}
private static String savePictureToFileSystem(byte[] data) {
File file = getOutputMediaFile();
saveToFile(data, file);
return file.getAbsolutePath();
}
private void setResult(String path) {
Intent intent = new Intent();
intent.putExtra(EXTRA_IMAGE_PATH, path);
setResult(RESULT_OK, intent);
}
*Credit to Paul Blundell
(...)
What do I need to do so that the main activity can receive the image's URI in the onactivityresult instead of the path String? Are URIs even applicable when it comes to custom cameras?
Please and thanks.
You use custom camera, but want to do it via Intent? OK, you have the absolute file path in
String abspath = data.getExtras().getString(EXTRA_IMAGE_PATH);
mMediaUri = Uri.fromFile(new File(abspath));

How to show file chooser when button is clicked?

I am trying to upload image in my app and i want to show some choices when my upload button is clicked. Unfortunately it gives me this error. I dont know what is wrong with the code. I got this from hereTrying open a specific folder in android using intent
thanks in advance!
uploadpic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
openFolder();
}
});
}
public void openFolder()
{
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
Uri uri = Uri.parse(Environment.getExternalStorageDirectory().getPath()
+ "/Pictures/");
intent.setDataAndType(uri, "images");
startActivity(Intent.createChooser(intent, "Open folder"));
takephoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
dispatchTakePictureIntent();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
profpic.setImageBitmap(imageBitmap);
}
}
static final int REQUEST_IMAGE_CAPTURE = 1;
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
You only want the user to select an image, am I right? Then maybe a general file picker isn't whats best suited for your needs.
A quick google search came up with this (also from SO). It seems like that solution is limited to pictures on an SD card.
If you don't want to click the link:
This is how you would start an intent in order to get an image.
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, SELECT_PHOTO);
You'll then need to override onActivityResult(), but this is all described in the link.

onActivityResult() only triggers when Camera is cancelled

I'm having some trouble using the Camera intent in Android. I want to be able to take
a picture and to use the picture later (retreiving the URI). Here's the code:
newPicBut.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
PhotoChoiceActivity.this.launchCameraIntent();
}
});
public void launchCameraIntent()
{
//create camera intent
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//set fileUri
MediaManager manager = new MediaManager();
manager.setPictureName(currentItemToAdd.toString());
intent.putExtra(MediaStore.EXTRA_OUTPUT, manager.getOutputMediaFileUri());
startActivityForResult(intent, 100);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
if(requestCode == 100){
if(resultCode == RESULT_OK){
Toast.makeText(getApplicationContext(), "Image saved to: " + data.getData(), Toast.LENGTH_LONG).show();
}
}
}
So basically the button calls the launchCameraIntent() method. The MediaManager creates a file, and I use the file URI in the intent.putExtra to indicate where the file should be saved. The Camera intent is called, but here is the problem: the onActivityResult() only gets triggered when I cancel my camera intent. So it doesn't get triggered at all when I accept the picture that I've taken.
Hope you can help!

Categories

Resources