Real-time image capture and preview with Android Camera2 camera API

Source: Internet
Author: User

Recently want to do a client to the server push real-time screen of the function, first of all to consider two ideas, one is the client to the video stream push, mainly using RTSP and other streaming media protocols for transmission, and the other is to get the current screen through the camera, each frame as an object to separate transmission.

The purpose of the project is to achieve the ultimate goal is to deal with every frame of the real-time screen, you can consider the client push to the server, and then the server for frame resolution operation, but because there are many streaming media push frame at the end of the push stream or the service is more or less limited, there are very few fully open source projects, In addition to the transmission of the screen and the need for a portion of the data, still need to establish a connection for transmission, so temporarily shelved the program. Choose the second idea, get each frame of the screen, separate transmission.

To get a real-time picture, we have to call the camera on the Android device.

From API21, Android introduced the ANDROID.HARDWARE.CAMERA2 package to replace the original camera class, the original camera class is no longer recommended for use. The most important change in CAMERA2 is that the call to the camera is no longer simply instantiated, but instead is invoked in a way similar to a service request. Using Cameramanager to manage the camera service, it is necessary to establish a cameracapturesession to call the camera device cameradevices session, to achieve the call to the camera. And the Capturerequest.builder class is used to establish the actual invocation request, the specific parameter settings can also be implemented by this class (rather than directly set up the camera device), the purpose is to separate the camera control and the camera itself, the user can be different session according to different Configuration to use the camera.

We can combine specific code to analyze the process of camera invocation in the new API.

First we want to operate the camera device, we need to get an example of Cameramanager

Cameramanager Cameramanager; Cameramanager = (Cameramanager) getsystemservice (Context.camera_service);

We can call the Opencamera function to turn on the camera device

Cameramanager.opencamera (Cameraid, Cameracallback, MainHandler);

Here you need to pass in three parameters, Cameraid is the device number, Cameracallback controls the callback for the camera service, and the last parameter specifies the Handlerthread object

     cameraid = integer.tostring (Cameracharacteristics.lens_facing_front);           private CameraDevice.StateCallback  Cameracallback = new cameradevice.statecallback ()  {          @Override         public void onopened ( Cameradevice camera)  {            LOG.D ( "Cameracallback",  "camera opened");             cameraDevice = camera;             takepreview ();        }          @Override         public void ondisconnected ( Cameradevice cameradevice)  {             LOG.D ("Cameracallback",  "Camera  Disconnected ");             closecameradevice ();         }         @Override         public void onerror (CameraDevice cameraDevice,  int i)  {            LOG.D (" Cameracallback ", " Camera error ");             toast.maketext (pushersurface.this,  "camera turned on failed",  toast.length_short). Show ();         }    };

  callback function is used to specify the operation of different states when connecting the camera device. Here, we call the  takepreview () function to open a preview of the camera screen when the camera is successfully connected.

Private void takepreview ()  {    try {         final CaptureRequest.Builder previewRequestBuilder                 = cameradevice.createcapturerequest ( Cameradevice.template_preview);         previewrequestbuilder.addtarget (Surfaceholder.getsurface ());         previewrequestbuilder.addtarget ( Previewreader.getsurface ());         cameradevice.createcapturesession ( Arrays.aslist (Surfaceholder.getsurface (),                 previewreader.getsurface (),                 imagereader.getsurface ()), new  Cameracapturesession.statecallback ()  {             @Override              public void onconfigured (CameraCaptureSession  Cameracapturesession)  {                 if  (cameradevice == null)  return;                 mCameraCaptureSession =  cameracapturesession;                 try {                     previewrequestbuilder.set (capturerequest.control_af_mode,                              capturerequeSt. Control_af_mode_continuous_picture);                     previewrequestbuilder.set (Capturerequest.control_ae_mode,                              capturerequest.control_ae_mode_off);                      Capturerequest previewrequest = previewrequestbuilder.build ();                      Mcameracapturesession.setrepeatingrequest (Previewrequest, null, childhandler);                 } catch  ( Cameraaccessexception e)  {                     E.printstacktrace ();                 }            }              @Override              public void onconfigurefailed (cameracapturesession cameracapturesession)  {                 Toast.maketext (pushersurface.this,  "Configuration Failed",  toast.length_short). Show ();             }        },  Childhandler);    } catch  (cameraaccessexception e)  {         e.printstacktrace ();nbsp;   }} 

To get an image from a camera device, we first need to create a camera capture session. Function

The first parameter of createcapturesession (list, cameracapturesession.statecallback, Handler) passed in the list of views we wanted to draw, The second parameter passes in the state callback function that establishes the camera session, and the third parameter passes to the corresponding handler processor. Then we need to use capturerequest to define the specific parameters of the camera when capturing the image, such as whether to turn on the camera, autofocus, etc. Finally, the request is opened via Camracapturesession.setrepeatingrequest. This allows us to get a continuous image from the surface list in the Capturesession incoming list. Notice that

Previewrequestbuilder.addtarget (Surfaceholder.getsurface ());p Reviewrequestbuilder.addtarget ( Previewreader.getsurface ());

Here, in addition to the surfaceholder surface in the XML interface layout, a Previewreader surface is passed in.

Previewreader is a custom ImageReader object.

Previewreader = imagereader.newinstance (1080, 1920, IMAGEFORMAT.YUV_420_888, 2);         previewreader.setonimageavailablelistener (new  Imagereader.onimageavailablelistener ()  {              @Override             public void  onimageavailable (Imagereader imagereader)  {                 Image image = null;                 try {                     image =  imagereader.acquirelatestimage ();                    &nBsp LOG.D ("Previewlistener",  "Getpreviewimage");                     if  (image == null)  {                          return;                     }                     byte[] bytes =  Imageutil.imagetobytearray (image);                     if  (Pushflag == false)                           uploadimg (bytes);                 } finally {                      if  (image != null)  {                         image.close ();                     }                 }             }        } ,  mainhandler);

ImageReader is a class that lets us directly manipulate images that are drawn to surface. Here we have a continuous preview of the image from the camera device, which is what we see on the screen, their format is uncompressed yuv_420_888 type (the same if you want to manipulate the image after the shot, it will be set to JPEG format). We call Imagereader.acquirelatestimage or acquirenextimage to get the picture in the image queue. and perform the operation. Here I use a function to compress the image into byte[] format and call the UPLOADIMG function to upload to the server. In this way, the entire camera's call to the preview image processing is finished. It's a very similar picture, and I'm not going to stick it out here.

More Android developers are welcome to communicate.

This article is from the "Davidwillo blog" blog, make sure to keep this source http://davidwillo.blog.51cto.com/12613091/1908166

Real-time image capture and preview with Android Camera2 camera API

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.