开发者

How to launch the camera and take a picture

开发者 https://www.devze.com 2023-02-19 11:54 出处:网络
I\'m trying to make an Android demo. In the demo, I have to show t开发者_高级运维he camera in an activity and take a picture before advancing to another activity where I can see the camera with the pi

I'm trying to make an Android demo. In the demo, I have to show t开发者_高级运维he camera in an activity and take a picture before advancing to another activity where I can see the camera with the picture and a little menu.

How can I launch the camera and take a picture?


In my app I use the following code to Launch the camera:

public void imageFromCamera() {
    Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
    mImageFile = new File(Environment.getExternalStorageDirectory()+File.separator+"MyApp",  
            "PIC"+System.currentTimeMillis()+".jpg");
    mSelectedImagePath = mImageFile.getAbsolutePath();
    intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mImageFile));
    startActivityForResult(intent, TAKE_PICTURE);
}

This will save the image to the path mSelectedImagePath which is /sdcard/MyApp/.jpg.

Then you capture the return of the IMAGE_CAPTURE intent in onActivityResult and launch your activity to edit the image from there!

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_OK) {
        switch(requestCode) {
        case TAKE_PICTURE:
                    //Launch ImageEdit Activity
            Intent i = new Intent(this, ImageEdit.class);
                    i.putString("imgPath", "mSelectedImagePath");
                    startActivity(i);
            break;
        }
    }
}

Hope this helps!


There are quite a few tutorials online for this, here are a few examples:

Tutorial 1 Tutorial 2 Tutorial 3


Here is the code sample.

Uri mOutputFileUri;
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, mOutputFileUri); // URI of the file where pic will be stored

startActivityForResult(intent, TAKE_PICTURE_FROM_CAMERA);

Then in your onActivityResult just check the resultCode and get your image from mOutputFileUri.

You would also want to check for the external media presence and handle the issues with the camera application behavior for HTC devices.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号