Capturing Image from camera and displaying it in another activity in android - java

I am developing an application in which i want to capture the image from the camera and display it in another activity in an image view, my problem is that able to capture the image but after capturing i am redirected to first activity instead to second one.
Here is my Code..
PictureOptions.java
public void buttonCameraOpen(View view)
{
// create Intent to take a picture and return control to the calling application
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
// start the image capture Intent
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
}
private static Uri getOutputMediaFileUri(int type){
return Uri.fromFile(getOutputMediaFile(type));
}
/** Create a File for saving an image or video */
private static File getOutputMediaFile(int type){
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "Easy Heal");
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
// Create the storage directory if it does not exist
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
Log.d("MyCameraApp", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE){
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"IMG_"+ timeStamp + ".jpg");
} else {
return null;
}
return mediaFile;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Bitmap selectedphoto = null;
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE && resultCode == RESULT_OK && null!=data) {
// Image captured and saved to fileUri specified in the Intent
//selectedphoto = (Bitmap) data.getExtras().get("data");
Uri selectedImage = data.getData();
String [] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex);
File f =new File(filePath);
String filename = f.getName();
cursor.close();
selectedphoto = BitmapFactory.decodeFile(filePath);
Intent intent = new Intent(PictureOptions.this,ShowImage.class);
//intent.putExtra("data", selectedphoto);
intent.setData( selectedImage );
startActivity(intent);
} else if (resultCode == RESULT_CANCELED) {
// User cancelled the image capture
} else {
// Image capture failed, advise user
}
}
PictureOptions.xml
<Button
android:id="#+id/buttonCameraOpen"
android:layout_width="fill_parent"
android:layout_height="72dp"
android:layout_weight="0.35"
android:onClick="buttonCameraOpen"
android:text="#string/button_camera_open" />
ShowImage.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_image);
ImageView imageview = (ImageView)findViewById(R.id.ImageShow);
Uri imageUri = getIntent().getData();
//Bitmap selectedphoto =(Bitmap)this.getIntent().getParcelableExtra("data");
imageview.setImageURI(imageUri);
}
ShowImage.xml
<ImageView
android:id="#+id/ImageShow"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />

I finally found an awesome solution
This library is used to capture image from camera or select from gallery and return back image in File format in onActivityResult method, which can be used further in the application.
Use
EasyImage Library

Uri uriSavedImage=Uri.fromFile(new File("/sdcard/flashCropped.png"));
camera.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
startActivityForResult(camera, 1);
After clicking the image, check whether it exists or not. Then send the path to the image file to the next activity and display it via Bitmap.

Call the camera intent
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
then on activity for result use this
'case REQUEST_IMAGE_CAPTURE:
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
saveBitmap(imageBitmap);
mimageView1.setImageBitmap(imageBitmap);
mIntent.putExtra("ACTIVITY_CODE", 1);
startActivity(mIntent);
break;
the add this method in ur same class
public void saveBitmap(Bitmap bmp)
{
String file_path = Environment.getExternalStorageDirectory().getAbsolutePath() +"/DCIM";
try
{
File dir = new File(file_path);
if(!dir.exists())
dir.mkdirs();
File file = new File(dir, "time");
cameraUrl=file.getAbsolutePath();
FileOutputStream fOut = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.PNG, 100, fOut);
fOut.flush();
fOut.close();
}
catch (Exception e) {
Log.e("errr in ","inserting the image at parictular location");
}
}
then call this in ur another activity where u want the image
String valueC = getIntent().getExtras().getString("CAMERA");
Log.v("imageBitmap", ""+valueC);
Bitmap yourSelectedImageC = BitmapFactory.decodeFile(valueC);
mImgV_image.setImageBitmap(yourSelectedImageC);

I have same problem after spending 2 days finally i got the anwer
First activity
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK && data != null) {
Uri uri = data.getData();
Intent intent= new Intent(this,SecondActivity.class);
selfiSrc.putExtra("imgurl", uri );
startActivity(intent);
}
SecondActivity
Imageview iv_photo=(ImageView)findViewById(R.id.iv_photo);
Bundle extras= getIntent().getExtras();
if(extras!=null)
{
path = (Uri) extras.get("imgurl");
iv_photo.setImageURI(path);
}
Another way see my answer
Android - how can i transfer ImageView from one activity to another activity?

Related

How to display an image from the Gallery in an ImageView?

I created a button that lets the user choose between "Take picture with camera" and "Select picture from gallery".
When the picture is taken/chosen, I then display it in an ImageView of the next activity which I do by passing the URI of the file created to store the taken/selected picture.
It works as expected when the user takes a picture with his camera but when he selects an image from gallery, no image is shown in the next activity despite both intents (take a picture and select a picture) being coded the same.
My question(s): Why isn't the image displayed in the next activity ONLY when picked from the gallery ? Or how should I proceed to display it ?
Intent to open camera (working fine):
private void openCameraToTakePictureIntent() {
Log.d(TAG, "Method for Intent Camera started");
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.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
}
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this,
"com.emergence.pantherapp.fileprovider", photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
}
Intent to access gallery and pick an image:
private void openGalleryIntent() {
Log.d(TAG, "Method for Intent Gallery started");
Intent galleryIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI);
if (galleryIntent.resolveActivity(getPackageManager()) != null) {
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
}
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this,
"com.emergence.pantherapp.fileprovider", photoFile);
galleryIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(galleryIntent, PICK_IMAGE);
}
}
}
Then here's the onActivityResult: (currentPhotoPath is the absolute path of the file created to store the image)
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK && requestCode == 1) {
Log.d(TAG, currentPhotoPath);
Intent intent = new Intent(this, ModifyPictureActivity.class);
intent.putExtra("USER_IMAGE", currentPhotoPath);
startActivity(intent);
} else if (resultCode == Activity.RESULT_OK && requestCode == 2) {
Log.d(TAG, currentPhotoPath);
Intent intent = new Intent(this, ModifyPictureActivity.class);
intent.putExtra("USER_IMAGE", currentPhotoPath);
startActivity(intent);
}
}
Below is how the image is displayed in the following activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_modify_picture);
Intent intent = getIntent();
String imageUri = intent.getStringExtra("USER_IMAGE");
if (imageUri != null) {
Log.d(TAG, imageUri);
} else {
Log.d(TAG, "imageUri was null");
}
image = findViewById(R.id.picture);
image.setImageURI(Uri.parse(imageUri));
}
I made sure to have the READ_EXTERNAL_STORAGE in the manifest and the xml layout is just set to "match_parent" for height and width but I can add them if it's relevant.
Few Intent actions use EXTRA_OUTPUT. Mostly, that is an ACTION_IMAGE_CAPTURE thing.
More typically, an Intent for getting a piece of content (ACTION_PICK, ACTION_GET_CONTENT, ACTION_OPEN_DOCUMENT, ACTION_CREATE_DOCUMENT, ACTION_OPEN_DOCUMENT_TREE, etc.) return a Uri from the content supplier in the Intentdelivered toonActivityResult(). Given your implementation, that would be data.getData()to get thatUri`.
You can then use a ContentResolver and openInputStream() to get an InputStream on the content identified by the Uri. In your case, for example, you could use that InputStream to copy the bytes to a FileOutputStream to make your own local copy of the content.
Note that you only have short-term access to the content identified by the Uri.

Converting Bitmap into a valid Uri

I am developing an android app where user is selecting the image either from gallery or capture from camera. When user get the image from gallery i get the image uri then i pass this uri to other activity in string form. then in next activity i convert that string into uri and then uri into bitmap and set the image bitmap in imageview. Now when i capture the image from camera i get the image bitmap.
Now i want to convert this bitmap into valid uri and pass to next activity
if(requestCode==GET_FROM_GALLERY && resultCode == Activity.RESULT_OK) {
Uri selectedImage = data.getData();
System.out.println("URLLL "+selectedImage);
Log.v("PhotoActivity", "Captured image");
//Create intent
Intent intent = new Intent(MainActivity.this, FlagDisplayActivity.class);
intent.putExtra("URI", selectedImage.toString());
//Start Flag Display activity
startActivity(intent);
Log.v("PHOTO ACTIVITY", " uri: " + selectedImage);
}
if (requestCode == CAMERA_REQUEST && resultCode == Activity.RESULT_OK)
{
Bitmap photo = (Bitmap) data.getExtras().get("data");
Intent intent = new Intent(MainActivity.this, FlagDisplayActivity.class);
intent.putExtra("URI", photo);
//Start Flag Display activity
startActivity(intent);
}
This is how i get the uri in next activity
String imageUriString=getIntent().getStringExtra("URI");
final Uri selectedImage=Uri.parse(imageUriString);
and then convert the uri into bitmap like this
Bitmap bitmap = null;
try {
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(),
selectedImage);
} catch (IOException e) {
e.printStackTrace();
bitmap=StringToBitMap(imageUriString);
}
My main goal is to convert the bitmap into uri
You write your Bitmap into the local Cache of the Application and retrieve it from there.
Bitmap photo = (Bitmap) data.getExtras().get("data");// Get the Bitmap
val file = File(context.cacheDir,"CUSTOM NAME") //Get Access to a local file.
file.delete() // Delete the File, just in Case, that there was still another File
file.createNewFile()
val fileOutputStream = file.outputStream()
val byteArrayOutputStream = ByteArrayOutputStream()
photo.compress(Bitmap.CompressFormat.PNG,100,byteArrayOutputStream)
val bytearray = byteArrayOutputStream.toByteArray()
fileOutputStream.write(bytearray)
fileOutputStream.flush()
fileOutputStream.close()
byteArrayOutputStream.close()
val URI = file.toURI()
Now you can send the URI to another Activity as a String and retrieve the URI from the String and get the Bitmap from the URI.
Intent intent = new Intent(MainActivity.this, FlagDisplayActivity.class);
intent.putExtra("URI", URI.toString());
//Start Flag Display activity
startActivity(intent);
Provide the path of image it will provide you image uri
Uri selectedImageURI = data.getData();
File imageFile = new File(getRealPathFromURI(selectedImageURI));
Uri yourUri = Uri.fromFile(f);
Use the following function so you will get image
private String getRealPathFromURI(Uri contentURI) {
String result;
Cursor cursor = getContentResolver().query(contentURI, null, null, null, null);
if (cursor == null) { // Source is Dropbox or other similar local file path
result = contentURI.getPath();
} else {
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
result = cursor.getString(idx);
cursor.close();
}
return result;
}
Try this:
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
imageView.setImageBitmap(bitmap);

I can't save file to gallery after taking photo by camera by using the FileProvider for Android 7.1.1

I build my app with FileProvider and I want to save the image after I take it. But I can't find the image in the gallery.
I found these source codes from the Android Studio tutorial. I don't know what is the problem. I tried use debugger and I think the createFile() is correct. I also have my bitmap works. It can display the image I take but I can't add the image to the gallery.
I have this in my Manifest.xml
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.temp.test"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/file_paths"/>
</provider>
And in the file_paths.xml I have
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="external" path="Android/data/com.temp.test/files/Pictures" />
</paths>
This is how I write the activity
private String mCurrentPhotoPath;
private ImageView mImageView;
private ImageButton StartCameraBtn;
private File photoFile = null;
//requestCode
private static final int REQUEST_IMAGE_CAPTURE = 1;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_photo_note);
mImageView = (ImageView) findViewById(R.id.imageView);
StartCameraBtn = (ImageButton) findViewById(R.id.StartCamera);
StartCameraBtn.setOnClickListener(this);
}
public void onClick(View view)
{
clearAllFocus();
switch (view.getId())
{
case R.id.StartCamera:
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null)
{
try
{
photoFile = createFile();
}
catch (IOException e)
{
e.printStackTrace();
}
if(photoFile != null){
Uri photoURI = FileProvider.getUriForFile(this,
"com.temp.test",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
break;
...
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
mImageView.setImageBitmap(null);
switch (requestCode)
{
case REQUEST_IMAGE_CAPTURE:
if (resultCode == RESULT_OK)
{
setPic();
galleryAddPic();
}
break;
}
}
private File createFile() throws IOException
{
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = image.getAbsolutePath();
return image;
}
private void galleryAddPic()
{
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(mCurrentPhotoPath);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
}
private void setPic()
{
// Get the dimensions of the View
int targetW = mImageView.getWidth();
int targetH = mImageView.getHeight();
// Get the dimensions of the bitmap
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
int photoW = bmOptions.outWidth;
int photoH = bmOptions.outHeight;
// Determine how much to scale down the image
int scaleFactor = Math.min(photoW/targetW, photoH/targetH);
// Decode the image file into a Bitmap sized to fill the View
bmOptions.inJustDecodeBounds = false;
bmOptions.inSampleSize = scaleFactor;
bmOptions.inPurgeable = true;
Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
mImageView.setImageBitmap(bitmap);
}
Please help! Thank you!
I use debugger to test the galleryaddpic() and the URI has been accessed sucessfully, but I don't know why I can't add it to the gallery. I can't find the image file in the android VM directory either.
This is the debug log:
https://i.stack.imgur.com/JN9uJ.png
I'm using chickendinner as my domian, and keep is the name of my app.
Thank you!
Call this function in onActivityResult. It worked for me!
It is in fragment.In activity you can use "this" instead of "getActivity()".
private void galleryAddPic() {
File f = new File(imageFilePath); //set your picture's path
try {
MediaStore.Images.Media.insertImage(getActivity().getContentResolver(),
f.getAbsolutePath(), f.getName(), null);
getActivity().sendBroadcast(new Intent(
Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(f)));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
Your code handles
write new photo as a jpg-file to the filesystem
add new photo to media-db via broadcst Intent.ACTION_MEDIA_SCANNER_SCAN_FILE
create a FileProvider that allow other apps to access private //Android/data/com.temp.test/files/Pictures/... files through a content-uri content://com.temp.test/...
I assume that the media-db scanner has no read-permission to your app-s private data directory Android/data/com.temp.test/files/Pictures via a file-uri and therefore cannot add the new photo to media-db.
Whatsapp and other apps store their received/send photo in public readable internal memory (i.e. /sdcard/PICTURES/WhatsApp/ ) where the media scanner can read it via file-uri via Intent.ACTION_MEDIA_SCANNER_SCAN_FILE.
I donot know, if the media scanner can handle content: -uris instead of file uri-s: You can try this:
private void galleryAddPic()
{
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
// assume that mCurrentPhotoPath ="Android/data/com.temp.test/files/Pictures/myTestImage.jpg"
// can be accessed from outside as "content://com.temp.test/myTestImage.jpg"
Uri contentUri = Uri.parse("content://com.temp.test/myTestImage.jpg");
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
}
Please let us know if this works.
If this does not work you can try to manually insert a "content://com.temp.test/..." entry into media database.
using public readable internal memory directories should work without a fileprovider

BitmapFactory: Unable to decode stream: java.io.FileNotFoundException even when file IS actually there

I'm creating a simple app to take a picture. this is my code
Button b1;
ImageView iv;
String TAG = "MAIN ACTIVITY";
File photo;
private Uri mImageUri;
private File createTemporaryFile(String part, String ext) throws Exception {
File externalStorageDirectory = Environment.getExternalStorageDirectory();
File tempDir = new File(externalStorageDirectory + "/cameratest/");
if (!tempDir.exists()) {
tempDir.mkdir();
}
return File.createTempFile(part, ext, tempDir);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1 = (Button) findViewById(R.id.button);
iv = (ImageView) findViewById(R.id.imageView);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
try {
// place where to store camera taken picture
photo = createTemporaryFile("picture", ".jpg");
photo.delete();
} catch (Exception e) {
Log.v(TAG, "Can't create file to take picture!");
Toast.makeText(getApplicationContext(), "Please check SD card! Image shot is impossible!",
Toast.LENGTH_SHORT).show();
}
mImageUri = Uri.fromFile(photo);
intent.putExtra(MediaStore.EXTRA_OUTPUT, mImageUri);
startActivityForResult(intent, 0);
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 0 && resultCode == RESULT_OK) {
Log.d(TAG, mImageUri.toString());
Bitmap bitmap = BitmapFactory.decodeFile(mImageUri.toString());
iv.setImageBitmap(bitmap);
}
}
as you can see i've added eLog.d(TAG, mImageUri.toString()); at the end and in the logcat (as well as the FileNotFoundException) i see this direcory:
03-27 00:43:30.498 30526-30526/myapplication.example.falcoleo.cameratest1 D/MAIN ACTIVITY: file:///storage/emulated/0/cameratest/picture459838058.jpg
03-27 00:43:30.499 30526-30526/myapplication.example.falcoleo.cameratest1 E/BitmapFactory: Unable to decode stream: java.io.FileNotFoundException: file:/storage/emulated/0/cameratest/picture459838058.jpg: open failed: ENOENT (No such file or directory)
guess if this directory exists?
spoler alert, it does. And it's not like the image is created after the BitmapFactory.decodeFile. I really do not understand what i'm doing wrong. Everything works fine except when it actually has to display the photo, then it just does not display it. just blank. Like WTF m8 i'm just trying to do my job no need to go crazy, you know.
Replace mImageUri.toString() with mImageUri.getPath().
decodeFile expects a path, not an uri string.
file:///storage/emulated/0/cameratest/picture459838058.jpg
Remove file:// because the decodeFile() expects a file system path.
/storage/emulated/0/cameratest/picture459838058.jpg
Use BitmapFactory.decodeStream instead of BitmapFactory.decodeFile.
try ( InputStream is = new URL( file_url ).openStream() ) {
Bitmap bitmap = BitmapFactory.decodeStream( is );
}
Source https://stackoverflow.com/a/28395036/5714364
Ok for me it was the file path was wrong so I needed to get the real filepath.
First
File file = new File(getPath(uri));
public String getPath (Uri uri)
{
String[] projection = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(uri,
projection,
null,
null,
null);
if (cursor == null)
return null;
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String s = cursor.getString(column_index);
cursor.close();
return s;
}
Then Back To Uri
Uri newUri = Uri.fromFile(file);
This conversion to file and back to uri did the trick for me. I was receiving simple data from action.SEND.

get image uri from Intent(MediaStore.ACTION_IMAGE_CAPTURE)

Hi when I do something like this
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
In onActivityResult I get thumbnail of the image from the data intent from the camera app
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
mImageView.setImageBitmap(imageBitmap);
And I use that bitmap something like this.
But What if I want the imageuri so that I can get the full size image from it. I tried getting the image uri from the intent something like above
Uri uri = data.getData();
if (uri != null) {
Log.d(TAG, uri.toString());
}else{
Log.d(TAG,"uri is null");
}
Doing like this I get uri is null in my logcat.So can anyone let me know how to get the image uri.I dont want to use EXTRA_OUTPUT and specify my own path.Thanks in advance
There is a well documented bug, which occurs in low resolution devices. Check this thread for the workaround.
There's a bug with that intent in some devices. Take a look at this to know how to workaround it.
In some devices, the Uri is null in onActivityForResult(). So you need
to set Uri to placing the captured image.
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// If there any applications that can handle this intent then call the intent.
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
Uri fileUri = Uri.fromFile(getOutputMediaFile());
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(takePictureIntent, CAMERA_PICKER);
}
public File getOutputMediaFile() {
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
File mediaStorageDir;
// If the external directory is writable then then return the External pictures directory.
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "MyApp");
} else {
mediaStorageDir = Environment.getDownloadCacheDirectory();
}
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d("MyCameraApp", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
File mediaFile;
mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_" + timeStamp + ".jpg");
return mediaFile;
}

Categories

Resources