How to Get Camera Result as a Uri in Data Folder

How to get camera result as a uri in data folder?

There are two ways to solve this problem.

1. Save bitmap which you received from onActivityResult method

You can start camera through intent to capture photo using below code

Intent cameraIntent=new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);

After capture photo, you will get bitmap in onActivityResult method

if (requestCode == CAMERA_REQUEST) {  
Bitmap photo = (Bitmap) data.getExtras().get("data");
}

Now you can simply save this bitmap to internal storage

Note: Here bitmap object consists of thumb image, it will not have a full resolution image

2. Save bitmap directly to internal storage using content provider

Here we will create content provider class to allow permission of local storage directory to camera activity

Sample provider example as per below

public class MyFileContentProvider extends ContentProvider {
public static final Uri CONTENT_URI = Uri.parse
("content://com.example.camerademo/");
private static final HashMap<String, String> MIME_TYPES =
new HashMap<String, String>();

static {
MIME_TYPES.put(".jpg", "image/jpeg");
MIME_TYPES.put(".jpeg", "image/jpeg");
}

@Override
public boolean onCreate() {

try {
File mFile = new File(getContext().getFilesDir(), "newImage.jpg");
if(!mFile.exists()) {
mFile.createNewFile();
}
getContext().getContentResolver().notifyChange(CONTENT_URI, null);
return (true);
} catch (Exception e) {
e.printStackTrace();
return false;
}

}

@Override
public String getType(Uri uri) {
String path = uri.toString();

for (String extension : MIME_TYPES.keySet()) {
if (path.endsWith(extension)) {
return (MIME_TYPES.get(extension));
}
}
return (null);
}

@Override
public ParcelFileDescriptor openFile(Uri uri, String mode)
throws FileNotFoundException {

File f = new File(getContext().getFilesDir(), "newImage.jpg");
if (f.exists()) {
return (ParcelFileDescriptor.open(f,
ParcelFileDescriptor.MODE_READ_WRITE));
}
throw new FileNotFoundException(uri.getPath());
}
}

After that you can simply use the URI to pass to camera activity using the below code

Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
i.putExtra(MediaStore.EXTRA_OUTPUT, MyFileContentProvider.CONTENT_URI);
startActivityForResult(i, CAMERA_RESULT);

If you don't want to create your own provider then you can use FileProvider from support-library-v4. For detailed help you can look into this post

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 the path or uri of the original Image captured by the camera.

You did not show the Intent that you used. I am assuming that it is ACTION_IMAGE_CAPTURE.

How to get the path or uri of the original Image captured by the camera

You don't, unless you supply the Uri to use via EXTRA_OUTPUT.

when i use the following code it returns me the thumbnail image

If you do not provide EXTRA_OUTPUT, ACTION_IMAGE_CAPTURE is supposed to give you a thumbnail.

I have already tried this method you said... it gives an error

Then perhaps you should ask a separate Stack Overflow question where you provide the code that you used and explain in detail what the problem was. This sample app demonstrates the use of ACTION_IMAGE_CAPTURE with EXTRA_OUTPUT.

there is original image in the gallery

There are ~2 billion Android devices, spread across ~10,000 device models. There are dozens, if not hundreds, of pre-installed camera apps. There are dozens, if not hundreds, of additional camera apps that the user can install from the Play Store and elsewhere. Your request could be handled by any of them, so do not assume that the behavior of one camera app is the same as the behavior for all of them.

There is no requirement for a camera app to write a full-size image to disk when a third-party app makes an ACTION_IMAGE_CAPTURE request for a thumbnail. In fact, I would consider it to be a bug if they do write out a full size image in that scenario.

Get uri from camera intent in android

If your device does not respect cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, you still can use

Uri imageUri = data.getData();

in onActivityResult(int requestCode, int resultCode, Intent data). But in most cases, the problem is that RAM is limited, and the system destroys your activity to give enough memory to the camera app to fulfill your intent. Therefore, when the result is returned, the fields of your activity are not initialized, and you should follow Amit's suggestion and implement onSavedInstance() and onRestoreInstanceState().

Retrieving a Content Uri from Camera Intent

I resolved it by performing a Media Scan on the item. From there I could get the content Uri (the extra complication of the handler in the code below is because I needed my result to be handled on the UI thread as it manipulated views):

private Uri mCameraFilePath;
private Context mContext;
...

private void handlePictureFromCamera(Intent data) {

MyMediaScannerClient client = new MyMediaScannerClient(
mCameraFilePath.getPath(), new Handler(), new OnMediaScanned() {

@Override
public void mediaScanned(Uri contentUri) {
//Here I have the content uri as its now in the media store
}
});
MediaScannerConnection connection = new MediaScannerConnection(mContext, client);
client.mConnection = connection;
connection.connect();
}

private interface OnMediaScanned {
public void mediaScanned(Uri contentUri);
}

/**
* This is used to scan a given file (image in this case) to ensure it is added
* to the media store thus making its content uri available. It returns the
* content form Uri by means of a callback on the supplied handler's thread.
*/
private class MyMediaScannerClient implements MediaScannerConnectionClient {

private final String mPath;
private MediaScannerConnection mConnection;
private final OnMediaScanned mFileScannedCallback;
private final Handler mHandler;

public MyMediaScannerClient(String path, Handler handler, OnMediaScanned fileScannedCallback) {
mPath = path;
mFileScannedCallback = fileScannedCallback;
mHandler = handler;
}

@Override
public void onMediaScannerConnected() {
mConnection.scanFile(mPath, null);
}

@Override
public void onScanCompleted(String path, final Uri uri) {

mConnection.disconnect();
mHandler.post(new Runnable() {

@Override
public void run() {
mFileScannedCallback.mediaScanned(uri);
}
});
}
}

Get Image From Camera result null in data onActivityResult

while you are capture image from the camera you have created a file for an image that is your image full path so make it globally.

 Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (cameraIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
Log.i(TAG, "IOException");
}
// Continue only if the File was successfully created
if (photoFile != null) {
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
startActivityForResult(cameraIntent, REQUEST_IMAGE_CAPTURE);
}
}

and the image file, mCurrentPhotoPath is the full path of image

  private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, // prefix
".jpg", // suffix
storageDir // directory
);

// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = "file:" + image.getAbsolutePath();
return image;
}

after onActivityResult() you get the image from mCurrentPhotoPath

    @Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
try {
mImageBitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), Uri.parse(mCurrentPhotoPath));
mImageView.setImageBitmap(mImageBitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}

For more info, you can check this link Capture Image from Camera and Display in Activity

In Nougat Capture Image from Camera and get file from Uri


How can i parse the Uri to get File

You don't. Moreover, you do not need to. Your file is whatever AppGlobal.getOutputMediaFile() returns. You need to hold onto that value (including putting it in the saved instance state Bundle, in case your process is terminated while the camera app is in the foreground). See this sample app for how to use ACTION_IMAGE_CAPTURE with FileProvider.

Capture image with camera using FileProvider, how to store uri


and my reference of the Uri is null when I come back from the camera

Save that Uri in your saved instance state Bundle of whatever activity or fragment is calling startActivity() to start the ACTION_IMAGE_CAPTURE app. See this sample app for a complete implementation of an ACTION_IMAGE_CAPTURE request that does this.



Related Topics



Leave a reply



Submit