Controlling the camera control camera

Source: Internet
Author: User

Directly controlling a device camera requires a lot more code than requesting pictures or videos from existing Camera applications. however, if you want to build a specialized camera application or something fully integrated in your app UI, http://blog.csdn.net/sergeycao

Open the camera object

Getting an instance ofCameraObject is the first step in the process of directly controlling the camera. As Android's own camera application does, the recommended way to access the camera is to open
CameraOn a separate thread that's launched from
onCreate()
. This approach is a good idea since it can take a while and might bog down the UI thread. In a more basic implementation, opening the camera can be deferred to
onResume()Method To facilitate code reuse and keep the flow of control simple.

CallingCamera.open()Throws an exception if the camera is already in use by another application, so we wrap it in
tryBlock.

private boolean safeCameraOpen(int id) {    boolean qOpened = false;      try {        releaseCameraAndPreview();        mCamera = Camera.open(id);        qOpened = (mCamera != null);    } catch (Exception e) {        Log.e(getString(R.string.app_name), "failed to open Camera");        e.printStackTrace();    }    return qOpened;    }private void releaseCameraAndPreview() {    mPreview.setCamera(null);    if (mCamera != null) {        mCamera.release();        mCamera = null;    }}

Since API level 9, the camera framework supports multiple cameras. If you use the legacy API and call
open()Without an argument, you get the first rear-facing camera.

Create the camera Preview

Taking a picture usually requires that your users see a preview of their subject before clicking the shutter. To do so, you can use
SurfaceViewTo draw previews of what the camera sensor is picking up.

Preview class

To get started with displaying a preview, you need preview class. The preview requires an implementation of
android.view.SurfaceHolder.CallbackInterface, which is used to pass image data from the camera hardware to the application.

class Preview extends ViewGroup implements SurfaceHolder.Callback {    SurfaceView mSurfaceView;    SurfaceHolder mHolder;    Preview(Context context) {        super(context);        mSurfaceView = new SurfaceView(context);        addView(mSurfaceView);        // Install a SurfaceHolder.Callback so we get notified when the        // underlying surface is created and destroyed.        mHolder = mSurfaceView.getHolder();        mHolder.addCallback(this);        mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);    }...}

The preview class must be passed toCameraObject before the live image preview can be started, as shown in the next section.

Set and start the preview

A camera instance and Its Related preview must be created in a specific order, with the camera object being first. In the snippet below, the process of initializing the camera is encapsulated so that
Camera.startPreview()Is called bysetCamera()Method, whenever the user does something to change the camera. The preview must also be restarted in the preview class
surfaceChanged()Callback method.

public void setCamera(Camera camera) {    if (mCamera == camera) { return; }        stopPreviewAndFreeCamera();        mCamera = camera;        if (mCamera != null) {        List<Size> localSizes = mCamera.getParameters().getSupportedPreviewSizes();        mSupportedPreviewSizes = localSizes;        requestLayout();              try {            mCamera.setPreviewDisplay(mHolder);        } catch (IOException e) {            e.printStackTrace();        }              /*          Important: Call startPreview() to start updating the preview surface. Preview must           be started before you can take a picture.          */        mCamera.startPreview();    }}
Modify camera settings

Camera settings change the way that the camera takes pictures, from the zoom level to exposure compensation. This example changes only the preview size; see the source code of the camera application for more.

public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {    // Now that the size is known, set up the camera parameters and begin    // the preview.    Camera.Parameters parameters = mCamera.getParameters();    parameters.setPreviewSize(mPreviewSize.width, mPreviewSize.height);    requestLayout();    mCamera.setParameters(parameters);    /*      Important: Call startPreview() to start updating the preview surface. Preview must be      started before you can take a picture.    */    mCamera.startPreview();}
Set the preview Orientation

Most camera applications lock the display into Landscape mode because that is the natural orientation of the camera sensor. this setting does not prevent you from taking portrait-mode photos, because the orientation of the device is recorded in the EXIF
Header.setCameraDisplayOrientation()Method lets you change how the preview is displayed without affecting how the image is recorded. However, in Android prior to API Level 14, you must stop your preview before changing
Orientation and then restart it.

Take a picture

UseCamera.takePicture()Method To take a picture once the preview is started. You can create
Camera.PictureCallbackAndCamera.ShutterCallbackObjects and pass them
Camera.takePicture().

If you want to grab images continously, you can createCamera.PreviewCallbackThat implements
onPreviewFrame(). For something in between, you can capture only selected preview frames, or set up a delayed action to call
takePicture().

Restart the preview

After a picture is taken, you must restart the preview before the user can take another picture. In this example, the restart is done by overloading the shutter button.

@Overridepublic void onClick(View v) {    switch(mPreviewState) {    case K_STATE_FROZEN:        mCamera.startPreview();        mPreviewState = K_STATE_PREVIEW;        break;    default:        mCamera.takePicture( null, rawCallback, null);        mPreviewState = K_STATE_BUSY;    } // switch    shutterBtnConfig();}
Stop the preview and release the camera

Once your application is done using the camera, it's time to clean up. In particle, you must release
CameraObject, or you risk crashing other applications, including new instances of your own application.

When should you stop the preview and release the camera? Well, having your preview surface destroyed is a pretty good hint that it's time to stop the preview and release the camera, as shown in these methods from
PreviewClass.

public void surfaceDestroyed(SurfaceHolder holder) {    // Surface will be destroyed when we return, so stop the preview.    if (mCamera != null) {        /*          Call stopPreview() to stop updating the preview surface.        */        mCamera.stopPreview();    }}/**  * When this function returns, mCamera will be null.  */private void stopPreviewAndFreeCamera() {    if (mCamera != null) {        /*          Call stopPreview() to stop updating the preview surface.        */        mCamera.stopPreview();            /*          Important: Call release() to release the camera for use by other applications.           Applications should release the camera immediately in onPause() (and re-open() it in          onResume()).        */        mCamera.release();            mCamera = null;    }}

Earlier in the lesson, this procedure was also part ofsetCamera()Method, so initializing a camera always begins with stopping the preview.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.