Android camera intent
Asked Answered
C

7

100

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?

Coronograph answered 28/4, 2010 at 12:12 Comment(1)
Refer the below link #13977745Penology
C
182
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());
            }
        }
    }
}
Coronograph answered 29/4, 2010 at 13:43 Comment(13)
Is there exist ability to open a front camera of device from intent??Lolitaloll
This works great, although you may need: private static int TAKE_PICTURE = 1;Mcdonald
@Aleksander O. - great code, thank you! i posted a complete fully functional implementation of this at https://mcmap.net/q/212657/-how-do-you-get-a-simple-camera-program-working-for-androidRoyston
NOT WORKING ON GALAXY S PHONES :(Dermatoplasty
Why 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?Wearisome
@kilaka, MediaStore.ACTION_IMAGE_CAPTUREDepositor
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.Ark
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.Finkle
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.Radiophotograph
Not worked on Xperia UL. imageUri and selectedImage will be null and Nullpointer Exception will occur.Plenary
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().Plenary
use this : Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);Backstop
You might need to use FileProvider in Android > M. See hereBlithe
C
22

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();
    // ...
  }
}
Cityscape answered 28/4, 2010 at 12:32 Comment(4)
Thanks 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);Coronograph
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?Cityscape
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.Coronograph
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.Camphorate
A
8

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.

Amorette answered 10/8, 2015 at 22:50 Comment(1)
Same for me. You saved me a few hours I suppose. Any idea why the Android Dev code is giving an IO exception?Panayiotis
F
2

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.

Frowst answered 31/5, 2018 at 16:16 Comment(0)
A
0

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);
        }
    });
}
Acey answered 11/1, 2018 at 9:12 Comment(1)
In this library there is no way to set output path for photo and there are also some bugs as it seemed to meAshaashamed
D
0

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();

     }
 }
Diecious answered 31/8, 2022 at 19:12 Comment(0)
L
-3

try this code

Intent photo= new Intent("android.media.action.IMAGE_CAPTURE");
                    startActivityForResult(photo, CAMERA_PIC_REQUEST);
Lakendra answered 12/6, 2014 at 15:35 Comment(1)
This 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?Deutschland

© 2022 - 2024 — McMap. All rights reserved.