I need to push an intent to default camera application to make it take a photo, save it and return an URI. Is there any way to do this?
-
Refer the below link http://stackoverflow.com/questions/13977245/android-open-camera-from-button/40041381#40041381 – Karthik Sridharan Oct 14 '16 at 11:13
7 Answers
private static final int TAKE_PICTURE = 1;
private Uri imageUri;
public void takePhoto(View view) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File photo = new File(Environment.getExternalStorageDirectory(), "Pic.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photo));
imageUri = Uri.fromFile(photo);
startActivityForResult(intent, TAKE_PICTURE);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case TAKE_PICTURE:
if (resultCode == Activity.RESULT_OK) {
Uri selectedImage = imageUri;
getContentResolver().notifyChange(selectedImage, null);
ImageView imageView = (ImageView) findViewById(R.id.ImageView);
ContentResolver cr = getContentResolver();
Bitmap bitmap;
try {
bitmap = android.provider.MediaStore.Images.Media
.getBitmap(cr, selectedImage);
imageView.setImageBitmap(bitmap);
Toast.makeText(this, selectedImage.toString(),
Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(this, "Failed to load", Toast.LENGTH_SHORT)
.show();
Log.e("Camera", e.toString());
}
}
}
}

- 2,595
- 1
- 14
- 16

- 19,190
- 11
- 37
- 51
-
-
5This works great, although you may need: private static int TAKE_PICTURE = 1; – Chris Rae Nov 16 '12 at 02:24
-
@Aleksander O. - great code, thank you! i posted a complete fully functional implementation of this at http://stackoverflow.com/a/13446838/1166727 – tony gil Nov 19 '12 at 02:50
-
11
-
1Why the hard coded 'android.media.action.IMAGE_CAPTURE'. It may not work on some phones. Is there a standard for this? Perhaps something around Intent.ACTION_GET_CONTENT? – AlikElzin-kilaka Feb 13 '13 at 11:47
-
7
-
Crucial to the successful functioning of this code is the TAKE_PICTURE static int request code. It would be helpful if you told readers what value that holds. – Andrew S May 27 '13 at 13:58
-
working on HTC one. Although, I had to remove the "TAKE_PICTURE" constant in the case and put in a contant "1" instead. Android was complaining about the lack of a constant here. – newshorts Jul 22 '13 at 07:14
-
There is a bug with Samsung devices, it wouldn't show the pictures taken from your app although it'll be saved in the Gallery. – San Dec 17 '13 at 15:09
-
Not worked on Xperia UL. imageUri and selectedImage will be null and Nullpointer Exception will occur. – Ataru Apr 30 '15 at 08:05
-
I found there was time lag. And I solved this issue by setting the delay by consuming Handler.postDelayed() so that imageUril variable couldn't be null in onActivityResult(). – Ataru Apr 30 '15 at 08:22
-
use this : Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); – Reza Bigdeli Sep 15 '15 at 10:45
-
2You might need to use `FileProvider` in Android > M. See [here](https://android.jlelse.eu/androids-new-image-capture-from-a-camera-using-file-provider-dd178519a954) – Nicolai Weitkemper Aug 03 '19 at 11:25
Try the following I found here
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
startActivityForResult(intent, 0);
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK && requestCode == 0) {
String result = data.toURI();
// ...
}
}

- 83,063
- 39
- 206
- 250

- 6,756
- 13
- 49
- 68
-
2Thanks but taken picture isn't saving to a device so I'm getting FileNotFoundException in Uri uri = Uri.parse(data.toURI()); bitmap = android.provider.MediaStore.Images.Media .getBitmap(contentResolver, uri); – Alexander Oleynikov Apr 28 '10 at 13:27
-
Are you saying the picture you take isn't being stored on the phone/device by your choice or something is happening and even though you tell it to store the image on your phone/device it acts like it's not saving? – Ryan Apr 28 '10 at 14:25
-
I'm saying that picture isn't being stored on device automatically but returns as a bitmap in onActivityResult(). However I've found a solution which I'll mention in an answer. – Alexander Oleynikov Apr 29 '10 at 13:40
-
This is the better answer. The top answer saves an unnecessary duplicate of the image. This appears in the user's gallery app as two images instead of one, which most people would consider to be a bug. – Thomas Dignan May 15 '13 at 18:49
It took me some hours to get this working. The code it's almost a copy-paste from developer.android.com, with a minor difference.
Request this permission on the AndroidManifest.xml
:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
On your Activity
, start by defining this:
static final int REQUEST_IMAGE_CAPTURE = 1;
private Bitmap mImageBitmap;
private String mCurrentPhotoPath;
private ImageView mImageView;
Then fire this Intent
in an onClick
:
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);
}
}
Add the following support method:
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;
}
Then receive the result:
@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();
}
}
}
What made it work is the MediaStore.Images.Media.getBitmap(this.getContentResolver(), Uri.parse(mCurrentPhotoPath))
, which is different from the code from developer.android.com. The original code gave me a FileNotFoundException
.

- 15,298
- 6
- 62
- 73
-
Same for me. You saved me a few hours I suppose. Any idea why the Android Dev code is giving an IO exception? – Coo Aug 09 '16 at 09:35
I found a pretty simple way to do this. Use a button to open it using an on click
listener to start the function openc()
, like this:
String fileloc;
private void openc()
{
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = null;
try
{
f = File.createTempFile("temppic",".jpg",getApplicationContext().getCacheDir());
if (takePictureIntent.resolveActivity(getPackageManager()) != null)
{
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,FileProvider.getUriForFile(profile.this, BuildConfig.APPLICATION_ID+".provider",f));
fileloc = Uri.fromFile(f)+"";
Log.d("texts", "openc: "+fileloc);
startActivityForResult(takePictureIntent, 3);
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 3 && resultCode == RESULT_OK) {
Log.d("texts", "onActivityResult: "+fileloc);
// fileloc is the uri of the file so do whatever with it
}
}
You can do whatever you want with the uri
location string. For instance, I send it to an image cropper to crop the image.

- 2,856
- 3
- 29
- 46

- 478
- 5
- 19
Try the following I found Here's a link
If your app targets M and above and declares as using the CAMERA permission which is not granted, then attempting to use this action will result in a SecurityException.
EasyImage.openCamera(Activity activity, int type);
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
EasyImage.handleActivityResult(requestCode, resultCode, data, this, new DefaultCallback() {
@Override
public void onImagePickerError(Exception e, EasyImage.ImageSource source, int type) {
//Some error handling
}
@Override
public void onImagesPicked(List<File> imagesFiles, EasyImage.ImageSource source, int type) {
//Handle the images
onPhotosReturned(imagesFiles);
}
});
}

- 874
- 14
- 25

- 1
- 1
-
In this library there is no way to set output path for photo and there are also some bugs as it seemed to me – Vlad Feb 11 '19 at 12:43
Call the camera through intent, capture images, and save it locally in the gallery.
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
someActivityResultLauncher.launch(cameraIntent);}
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
bitmap = (Bitmap) Objects.requireNonNull(result.getData()).getExtras().get("data");
}
imageView.setImageBitmap(bitmap);
saveimage(bitmap);
}
private void saveimage(Bitmap bitmap){
Uri images;
ContentResolver contentResolver = getContentResolver();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q){
images = MediaStore.Images.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY);
}else {
images = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
}
ContentValues contentValues = new ContentValues();
contentValues.put(MediaStore.Images.Media.DISPLAY_NAME, System.currentTimeMillis() +".jpg");
contentValues.put(MediaStore.Images.Media.MIME_TYPE, "images/*");
Uri uri = contentResolver.insert(images, contentValues);
try {
OutputStream outputStream = contentResolver.openOutputStream(Objects.requireNonNull(uri));
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
Objects.requireNonNull(outputStream);
//
}catch (Exception e){
//
e.printStackTrace();
}
}
try this code
Intent photo= new Intent("android.media.action.IMAGE_CAPTURE");
startActivityForResult(photo, CAMERA_PIC_REQUEST);

- 1,705
- 17
- 13
-
6This post is being automatically flagged as low quality because it is only code. Would you mind expanding it by adding some text to explain how it solves the problem? – gung - Reinstate Monica Jun 12 '14 at 16:18