There are of course, many ways on Android to take a picture or record a video. The easiest way to capture an image is by using an intent to launch the camera app and grabbing the results once the image has been taken.
Launching a camera intent typically goes like this:
activity_main.xml
layout, add a new button and an image view. Name the image view image
.takePicture
method from the event handler implementation.takePicture
method. If supported by the device, launch the capture intent:static final int REQUEST_IMAGE_CAPTURE = 1; private void takePicture() { Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); if (captureIntent.resolveActivity( getPackageManager()) != null) { startActivityForResult(captureIntent, REQUEST_IMAGE_CAPTURE); } }
onActivityResult
method. You will get the thumbnail from the data being returned and display the result in the image view:@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == REQUEST_IMAGE_CAPTURE &&resultCode == RESULT_OK) { Bundle extras = data.getExtras(); Bitmap thumbBitmap = (Bitmap) extras.get("data");"); ((ImageView)findViewById(R.id.image) ).setImageBitmap(thumbBitmap); } }
This is the easiest way to capture an image, and perhaps you have already done it this way before.
If you want to preview the image within your own app, there is more work to do. The Camera2 API can be used for previewing, capturing, and encoding purposes.
Within the Camera2 API, you will find components such as CameraManager
, CameraDevice
, CaptureRequest
, and CameraCaptureSession
.
Listed here are the most important Camera2 API classes:
Class |
Objectives |
---|---|
|
Select camera, create camera device |
|
|
|
Link to surface view (previewing) |
|
Capture an image and display it on the surface view |
The sample that we are going to investigate in the next recipe, Image capturing, may look a bit confusing at first. This is mostly because the setup process requires many steps, and most of them will be executed asynchronously. But do not worry, though - we will investigate it step by step.