Get Path of Image from Action_Image_Capture Intent

Get Path of image from ACTION_IMAGE_CAPTURE Intent

This is how it works on 2.2 (different than on previous versions). When starting intent

        String fileName = "temp.jpg";  
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, fileName);
mCapturedImageURI = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);

Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);
startActivityForResult(intent, CAPTURE_PICTURE_INTENT);

you need to remember mCapturedImageURI.

When you capture image, in onActivityResult() use that URI to obtain file path:

            String[] projection = { MediaStore.Images.Media.DATA}; 
Cursor cursor = managedQuery(mCapturedImageURI, projection, null, null, null);
int column_index_data = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String capturedImageFilePath = cursor.getString(column_index_data);

UPDATE: On new Android devices you would not need MediaStore.EXTRA_OUTPUT, but you rather deduce image/video URI from data.getData() received from onActivityResult(..., Intent data), as nicely described under

Android ACTION_IMAGE_CAPTURE Intent

However, since this part is subject to manufacturer adaptation, you may still encounter phones where "old" approach may be useful.

Getting path of captured image in Android using camera intent

Try like this

Pass Camera Intent like below

    Intent intent = new Intent(this);
startActivityForResult(intent, REQ_CAMERA_IMAGE);

And after capturing image Write an OnActivityResult as below

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
knop.setVisibility(Button.VISIBLE);


// CALL THIS METHOD TO GET THE URI FROM THE BITMAP
Uri tempUri = getImageUri(getApplicationContext(), photo);

// CALL THIS METHOD TO GET THE ACTUAL PATH
File finalFile = new File(getRealPathFromURI(tempUri));

System.out.println(mImageCaptureUri);
}
}

public Uri getImageUri(Context inContext, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
return Uri.parse(path);
}

public String getRealPathFromURI(Uri uri) {
String path = "";
if (getContentResolver() != null) {
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
path = cursor.getString(idx);
cursor.close();
}
}
return path;
}

And check log.

Edit:

Lots of people are asking how to not get a thumbnail. You need to add this code instead for the getImageUri method:


public Uri getImageUri(Context inContext, Bitmap inImage) {
Bitmap OutImage = Bitmap.createScaledBitmap(inImage, 1000, 1000,true);
String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), OutImage, "Title", null);
return Uri.parse(path);
}

The other method Compresses the file. You can adjust the size by changing the number 1000,1000

How to get image path from camera intent?

Its above code works in some mobile but does not work in samsung mobile in my case so I implemented the common logic for all devices.

When I capture the photo from camera so I implement a logic using Cursor and iterate the cursor and get the last photo path which is capture from camera.

Cursor cursor = getContentResolver().query(Media.EXTERNAL_CONTENT_URI, new String[]{Media.DATA, Media.DATE_ADDED, MediaStore.Images.ImageColumns.ORIENTATION}, Media.DATE_ADDED, null, "date_added ASC");
if(cursor != null && cursor.moveToFirst())
{
do {
uri = Uri.parse(cursor.getString(cursor.getColumnIndex(Media.DATA)));
photoPath = uri.toString();
}while(cursor.moveToNext());
cursor.close();
}

How to get uri of captured photo?

Follow below steps.

Step - 1 : Create provider_paths.xml in res/xml folder and write below code in it.

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path
name="external_files"
path="." />
</paths>

Step - 2 : Declare provider in manifest as below.

       <provider
android:name="android.support.v4.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provider_paths" />
</provider>

If you are facing error at: android:name="android.support.v4.content.FileProvider"
Use:

<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provider_paths" />
</provider>

Step - 3 : Write your camera intent as below.

    Intent m_intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File file = new File(Environment.getExternalStorageDirectory(), "MyPhoto.jpg");
Uri uri = FileProvider.getUriForFile(this, this.getApplicationContext().getPackageName() + ".provider", file);
m_intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, uri);
startActivityForResult(m_intent, REQUEST_CAMERA_IMAGE);

Step - 4 : Handle camera result in onActivityResult as below.

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {

//TODO... onCamera Picker Result
case REQUEST_CAMERA_IMAGE:
if (resultCode == RESULT_OK) {

//File object of camera image
File file = new File(Environment.getExternalStorageDirectory(), "MyPhoto.jpg");

//Uri of camera image
Uri uri = FileProvider.getUriForFile(this, this.getApplicationContext().getPackageName() + ".provider", file);

}
break;
}
}

How to get Image URI by intent MediaStore.ACTION_IMAGE_CAPTURE in Android 10 and above

This approach worked for me

In Manifest file

     <application>
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="com.example.android.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths">
</meta-data>
</provider>
...
</application

created a file /res/xml/file_paths.xml and specified path in that

<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-files-path name="my_images" path="Pictures" />
</paths>

In my activity

created a global variable var cameraPhotoFilePath: Uri? = null

this is how I started Camera acitivity for results

val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
val photoFile: File? = try {
createImageFileInAppDir()
} catch (ex: IOException) {
// Error occurred while creating the File
null
}

photoFile?.also { file ->
val photoURI: Uri = FileProvider.getUriForFile(
this,
"com.example.android.provider",
file
)
cameraPhotoFilePath = photoURI
intent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI)
}
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
startActivityForResult(intent, ACTION_REQUEST_CAMERA)

here is a helper function that i used in above code

@Throws(IOException::class)
private fun createImageFileInAppDir(): File {
val timeStamp: String = SimpleDateFormat("yyyyMMdd_HHmmss").format(Date())
val imagePath = getExternalFilesDir(Environment.DIRECTORY_PICTURES)
return File(imagePath, "JPEG_${timeStamp}_" + ".jpg")
}

At the end in onActivityResult thats how I got image Uri

if (resultCode == RESULT_OK && requestCode == ACTION_REQUEST_CAMERA) {
cameraPhotoFilePath?.let { uri ->
// here uri is image Uri that was captured by camera
}
}

fetch the path of an image stored in gallery after camera capture

Define custom methods for set and get captured image path :

private String imgPath;

public Uri setImageUri() {
// Store image in dcim
File file = new File(Environment.getExternalStorageDirectory() + "/DCIM/", "image" + new Date().getTime() + ".jpg");
Uri imgUri = Uri.fromFile(file);
imgPath = file.getAbsolutePath();
return imgUri;
}

public String getImagePath() {
return imgPath;
}

Set image uri to EXTRA_OUTPUT using capture intent :

captureImageIntent.putExtra(MediaStore.EXTRA_OUTPUT, setImageUri());

Get captured image bitamp from decoded capture image path :

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == RESULT_CAPTURE_IMAGE) {
imgUserImage.setImageBitmap(decodeFile(getImagePath()));
}
}
}

public Bitmap decodeFile(String path) {
try {
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, o);
// The new size we want to scale to
final int REQUIRED_SIZE = 70;

// Find the correct scale value. It should be the power of 2.
int scale = 1;
while (o.outWidth / scale / 2 >= REQUIRED_SIZE && o.outHeight / scale / 2 >= REQUIRED_SIZE)
scale *= 2;
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeFile(path, o2);
} catch (Throwable e) {
e.printStackTrace();
}
return null;
}


Related Topics



Leave a reply



Submit