Android Camera2 Photo (i)--using Surfaceview

Source: Internet
Author: User

Original: Android Camera2 photo (i)--using Surfaceview

CAMERA2 API Introduction

Android started from 5.0 (21), introduced a new camera API Camera2, the original Android.hardware.Camera was discarded (hereinafter referred to as CAMERA1), There is also a android.graphics.Camera, this android.graphics.Camera is not used for photography, is used to deal with the image, you can make 3D image effects and the like, before the Camera1 by Android.hardware.Camera generation For. The CAMERA2 supports raw output, can adjust the exposure, focus mode, shutter, etc., the function is more powerful than the original camera.

This refers to the concept of piping that connects the Android device to the camera, and the system sends the CAPTURE request to the camera, and the camera returns to Camerametadata. It's all based on a conversation called Cameracapturesession.

    • Cameramanaer camera manager, for detecting cameras, opening the system camera, calling Cameramanager.getcameracharacteristics (String) to get the relevant characteristics of the specified camera
    • Features of the Cameracharacteristics camera
    • Cameradevice camera, like Android.hardware.Camera, Camera1 's camera.
    • Cameracapturesession this kind of control camera preview or take pictures, setrepeatingrequest () Open preview, capture () take pictures, Cameracapturesession provides statecallback , capturecallback two interfaces to monitor the cameracapturesession creation and capture process.
    • Camerarequest and Camerarequest.builder, when previewing or taking pictures, require a Camerarequest object. Camerarequest represents a capture request that is used to set various parameters of a photo, such as focus mode, exposure mode, and so on. Camerarequest.builder is used to generate Camerarequest objects.
simple use of Camera2 (using Surfaceview)

Main steps:

    1. Get Camera Manager Cameramanager Mcameramanager,mcameramanager.opencamera () to turn on the camera
    2. Specify the camera you want to open and create the cameradevice.statecallback required for Opencamera () statecallback
    3. In Cameradevice.statecallback statecallback, call Takepreview (), in this method, Use Capturerequest.builder to create a preview of the required camerarequest, initialize the cameracapturesession, and finally call Setrepeatingrequest (previewrequest , NULL, Childhandler) was previewed
    4. Click the Take photo button, call Takepicture (), within this method, finally call capture (Mcapturerequest, NULL, Childhandler)
    5. In the new Imagereader.onimageavailablelistener () {} callback method, the picture taken by the photo is displayed

Package Org.hunter.a361camera.view;import Android. Manifest;import Android.content.context;import Android.content.pm.packagemanager;import Android.graphics.Bitmap; Import Android.graphics.bitmapfactory;import Android.graphics.imageformat;import Android.hardware.camera2.cameraaccessexception;import Android.hardware.camera2.cameracapturesession;import Android.hardware.camera2.cameracharacteristics;import Android.hardware.camera2.cameradevice;import Android.hardware.camera2.cameramanager;import Android.hardware.camera2.capturerequest;import Android.media.Image ; Import Android.media.imagereader;import android.os.build;import android.os.bundle;import Android.os.Handler; Import Android.os.handlerthread;import Android.support.annotation.nullable;import Android.support.annotation.requiresapi;import Android.support.v4.app.activitycompat;import Android.support.v4.app.fragment;import Android.util.sparseintarray;import Android.view.layoutinflater;import Android.view.surface;import Android.view.SurfaceHolder;import Android.view.surfaceview;import Android.view.view;import Android.view.viewgroup;import Android.widget.imageview;import Android.widget.toast;import Org.hunter.a361camera.r;import Java.nio.ByteBuffer; Import Java.util.arrays;import Static android.os.looper.getmainlooper;/** * Main UI for the statistics screen.    */public class Camerafragment extends Fragment {public static final int request_camera_code = 100;    public static final String package = "Package:";    Private static final Sparseintarray orientations = new Sparseintarray ();        To make the photo appear vertically static {Orientations.append (SURFACE.ROTATION_0, 90);        Orientations.append (surface.rotation_90, 0);        Orientations.append (surface.rotation_180, 270);    Orientations.append (surface.rotation_270, 180);    } private Surfaceview Msurfaceview;    Private Surfaceholder Msurfaceholder;    Private ImageView iv_show;    Private ImageView mcatture; Private Cameramanager mcameramanager;//Camera Manager privateHandler Childhandler, MainHandler;    Private String mcameraid;//Camera ID 0 for the rear 1 for the former private ImageReader Mimagereader;    Private Cameracapturesession mcameracapturesession;    Private Cameradevice Mcameradevice; /** * Camera Creation Monitor */private Cameradevice.statecallback statecallback = new Cameradevice.statecallback () {@            Override public void onopened (Cameradevice camera) {//Open camera Mcameradevice = camera;        Open preview Takepreview ();                 } @Override public void ondisconnected (Cameradevice camera) {//Turn off webcam if (null! = Mcameradevice) {                Mcameradevice.close ();            CameraFragment.this.mCameraDevice = null; }} @Override public void OnError (cameradevice camera, int error) {//Error toast.maketext (g        Etcontext (), "Camera turned on failed", Toast.length_short). Show ();    }    };    public static Camerafragment newinstance () {return new camerafragment ();   } @Nullable @Override public View oncreateview (layoutinflater inflater, ViewGroup container,        Bundle savedinstancestate) {View root = inflater.inflate (R.layout.camera_frag, container, false);        Initview (root);        Initlistener ();    return root;    } @Override public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);    } @Override public void Onresume () {super.onresume (); }/** * Initialize * * * private void Initview (View root) {iv_show = (ImageView) Root.findviewbyid (R.id.iv_sho        W_CAMERA2);        Msurfaceview Msurfaceview = (surfaceview) Root.findviewbyid (R.ID.SURFACE_VIEW_CAMERA2);        Mcatture = (ImageView) Root.findviewbyid (r.id.capture);        Msurfaceholder = Msurfaceview.getholder ();        Msurfaceholder.setkeepscreenon (TRUE);      Msurfaceview Add callback Msurfaceholder.addcallback (new Surfaceholder.callback () {@Override      public void surfacecreated (Surfaceholder holder) {//surfaceview created//Initialize camera INITCA            Mera2 ();            } @Override public void surfacechanged (surfaceholder holder, int format, int width, int height) {                } @Override public void surfacedestroyed (Surfaceholder holder) {//surfaceview destroyed                    Release the camera resource if (null! = Mcameradevice) {mcameradevice.close ();                CameraFragment.this.mCameraDevice = null;    }            }        }); }/** * Initializes the CAMERA2 */@RequiresApi (API = Build.version_codes.        LOLLIPOP) private void InitCamera2 () {Handlerthread handlerthread = new Handlerthread ("Camera2");        Handlerthread.start ();        Childhandler = new Handler (Handlerthread.getlooper ());        MainHandler = new Handler (Getmainlooper ());       Mcameraid = "" + cameracharacteristics.lens_facing_front;//Rear camera Mimagereader = Imagereader.newinstance (1920x1080, 1920x1080, Imageformat.jpeg, 1);            Mimagereader.setonimageavailablelistener (New Imagereader.onimageavailablelistener () {//can handle temporary photos taken here for example, write to local                @Override public void onimageavailable (ImageReader reader) {//mcameradevice.close ();                Get the photo image data image = Reader.acquirenextimage ();                Bytebuffer buffer = Image.getplanes () [0].getbuffer ();                byte[] bytes = new byte[buffer.remaining ()];                 Buffer.get (bytes);//buffers are stored in byte array final Bitmap Bitmap = bitmapfactory.decodebytearray (bytes, 0, bytes.length);                if (bitmap! = null) {Iv_show.setimagebitmap (bitmap);        }}}, MainHandler);        Get camera Management Mcameramanager = (Cameramanager) getcontext (). Getsystemservice (Context.camera_service); try {if (Activitycompat.checkselfpermission (GetContext (), MaNifest.permission.CAMERA)! = packagemanager.permission_granted) {//Apply Write_external_storage permissions                Requestpermissions (New String[]{manifest.permission.camera}, Request_camera_code);            Return            } else {//Open camera Mcameramanager.opencamera (Mcameraid, Statecallback, MainHandler);        }} catch (Cameraaccessexception e) {e.printstacktrace ();         }} @Override public void Onrequestpermissionsresult (int requestcode, string[] permissions, int[] grantresults) {        Super.onrequestpermissionsresult (Requestcode, permissions, grantresults);                if (Requestcode = = Request_camera_code) {if (grantresults[0] = = packagemanager.permission_granted) { Permission granted try {mcameramanager.opencamera (mcameraid, Statecallback, MA                Inhandler);        } catch (Cameraaccessexception e) {            E.printstacktrace ();                } catch (SecurityException e) {e.printstacktrace (); }} else {//Permission Denied}}}/** * Start preview */Private V OID Takepreview () {try {//Create preview required Capturerequest.builder final Capturerequest.builder Previ            Ewrequestbuilder = Mcameradevice.createcapturerequest (Cameradevice.template_preview); Surfaceview surface as the target of Capturerequest.builder Previewrequestbuilder.addtarget (Msurfaceholder.getsurface ())            ; Create Cameracapturesession, which manages processing preview requests and take picture requests mcameradevice.createcapturesession (Arrays.aslist (msurfaceholder.ge Tsurface (), Mimagereader.getsurface ()), New Cameracapturesession.statecallback ()//③{@Overrid e public void onconfigured (Cameracapturesession cameracapturesession) {if (null = = MCam     Eradevice) return;               When the camera is ready, start showing preview mcameracapturesession = cameracapturesession; try {//AF Previewrequestbuilder.set (Capturerequest.control_af_mode, Capt                        Urerequest.control_af_mode_continuous_picture); Turn on the Flash Previewrequestbuilder.set (Capturerequest.control_ae_mode, Capturerequest.control_ae_mode_o                        N_auto_flash);                        Display preview Capturerequest previewrequest = Previewrequestbuilder.build ();                    Mcameracapturesession.setrepeatingrequest (previewrequest, NULL, Childhandler);                    } catch (Cameraaccessexception e) {e.printstacktrace (); }} @Override public void onconfigurefailed (Cameracapturesession cameracaptur esession) {Toast.maketext (GetContext (), "Configuration Failed", Toast.length_short). ShoW ();        }}, Childhandler);        } catch (Cameraaccessexception e) {e.printstacktrace ();        }}/** * Photo * * * private void Takepicture () {if (Mcameradevice = = null) return;        Create the Capturerequest.builder final Capturerequest.builder Capturerequestbuilder required for the camera;            try {capturerequestbuilder = Mcameradevice.createcapturerequest (cameradevice.template_still_capture); Use ImageReader's surface as the target of the Capturerequest.builder Capturerequestbuilder.addtarget (Mimagereader.getsurface (            )); Autofocus Capturerequestbuilder.set (Capturerequest.control_af_mode, Capturerequest.control_af_mode_continuous_pic            TURE); AE Capturerequestbuilder.set (Capturerequest.control_ae_mode, Capturerequest.control_ae_mode_on_auto_flash)            ;            Get the phone direction int rotation = Getactivity (). Getwindowmanager (). Getdefaultdisplay (). Getrotation (); Depending on the device orientationCalculates the orientation of the set photo Capturerequestbuilder.set (Capturerequest.jpeg_orientation, Orientations.get (rotation));            Photo Capturerequest mcapturerequest = Capturerequestbuilder.build ();        Mcameracapturesession.capture (mcapturerequest, NULL, Childhandler);        } catch (Cameraaccessexception e) {e.printstacktrace (); }} private void Initlistener () {Mcatture.setonclicklistener (new View.onclicklistener () {@Overri            De public void OnClick (View v) {takepicture ();    }        }); }}

Layout file:

<?xml version= "1.0" encoding= "Utf-8"? ><relativelayout xmlns:android= "http://schemas.android.com/apk/res/ Android "Android:layout_width=" Match_parent "android:layout_height=" match_parent "> &lt ; Surfaceview android:id= "@+id/surface_view_camera2" android:layout_width= "Match_parent" android:layout        _height= "Match_parent"/> <org.hunter.a361camera.widget.porterduffviewimageview android:id= "@+id/capture"        Android:layout_width= "90DP" android:layout_height= "90DP" android:layout_alignparentbottom= "true" Android:layout_centerhorizontal= "true" android:layout_marginbottom= "20DP" android:src= "@mipmap/capture"/&G    T <org.hunter.a361camera.widget.porterduffviewimageview android:id= "@+id/iv_show_camera2" Android:layout_wi Dth= "80DP" android:layout_height= "80DP" android:layout_alignparentbottom= "true" ANDROID:LAYOUT_ALIGNP Arentright= "true" aNdroid:layout_marginbottom= "20DP" android:layout_marginright= "20DP" android:scaletype= "Centercrop"/></ Relativelayout>
Source code address: Https://github.com/gengqifu/361Camera. Welcome Fork/star


Android Camera2 Photo (i)--using Surfaceview

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.