Capturing images the easy way

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.

Getting ready

For this recipe, you just need to have Android Studio up and running.

How to do it...

Launching a camera intent typically goes like this:

  1. In Android Studio, create a new project.
  2. In the activity_main.xml layout, add a new button and an image view. Name the image view image.
  3. Create an on-click handler for that button.
  4. Call the takePicture method from the event handler implementation.
  5. Implement the 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);
       }
    }
  6. Override the 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.

There's more...

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

CameraManager

Select camera, create camera device

CameraDevice

Create CaptureRequest, CameraCaptureSession

CaptureRequest, CameraBuilder

Link to surface view (previewing)

CameraCaptureSession

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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset