Android Camera2 Photo (ii)--using Textureview

Source: Internet
Author: User

Original: Android Camera2 photo (ii)--using Textureview

The previous blog post briefly describes taking photos using the Camera2 API and using Surfaceview as the preview interface. In fact, compared to Surfaceview, Textureview is more suitable for video and photo shoots. Surfaceview also has its use occasions, which will be elaborated in another article. This article will use Textureview as the preview interface to show you the simple application of the Camera2 API again.

1, define Textureview as the preview interface

Add the Textureview control to the layout file and then implement its listener event

Textureview = (Textureview) Findviewbyid (R.id.textureview);
Then we can set the listener Surefacetexture event in the Onresume () method

Textureview.setsurfacetexturelistener (Texturelistener);

Callback Surfacetexturelistener's Onsurfacetextureavailable () method when Surefacetexture is ready.

Private Textureview.surfacetexturelistener Mtexturelistener = new Textureview.surfacetexturelistener () {        @ Override public        void onsurfacetextureavailable (surfacetexture surface, int width, int height) {            // When Surefacetexture is available, set the camera parameters and turn on the camera            setupcamera (width, height);            Opencamera ();        }        @Override public        void onsurfacetexturesizechanged (surfacetexture surface, int width, int height) {        }        @ Override Public        Boolean onsurfacetexturedestroyed (Surfacetexture surface) {            return false;        }        @Override public        void onsurfacetextureupdated (Surfacetexture surface) {        }    };
2. Set Camera parameters

private void Setupcamera (int width, int height) {//Get Camera Manager cameramanager Cameramanager manager = (Camerama        Nager) GetContext (). Getsystemservice (Context.camera_service); try {//Traverse all camera for (String cameraId:manager.getCameraIdList ()) {Cameracharacteris                Tics characteristics = manager.getcameracharacteristics (cameraid);                Integer facing = Characteristics.get (cameracharacteristics.lens_facing);                    The rear camera is turned on by default if (facing! = NULL && facing = = Cameracharacteristics.lens_facing_front)                Continue Get Streamconfigurationmap, which is all the output formats and dimensions supported by the management camera Streamconfigurationmap map = Characteristics.get (Camerachara Cteristics.                SCALER_STREAM_CONFIGURATION_MAP);                Assert map! = NULL; Set preview Size according to textureview size mpreviewsize = Getoptimalsize (map.getoutputsizes (surfacetexture.class), width, hei                Ght); BeenMaximum camera size mcapturesize = Collections.max (Arrays.aslist (map.getoutputsizes (Imageformat.jpeg)), new Compar                        Ator<size> () {@Override public int compare (size lhs, size RHS) {                    Return Long.signum (Lhs.getwidth () * Lhs.getheight ()-rhs.getheight () * rhs.getwidth ());                }                });                This imagereader is used for photographing the required setupimagereader ();                Mcameraid = Cameraid;            Break        }} catch (Cameraaccessexception e) {e.printstacktrace (); }    }

//select Sizemap greater than and closest to width and height of size private size getoptimalsize (size[] sizemap, int        width, int height) {list<size> sizelist = new arraylist<> (); for (Size Option:sizemap) {if (width > height) {if (Option.getwidth () > Width &&am P                Option.getheight () > height) {sizelist.add (option);                    }} else {if (Option.getwidth () > Height && option.getheight () > width) {                Sizelist.add (option); }}} if (Sizelist.size () > 0) {return collections.min (sizelist, New comparator< ; Size> () {@Override public int compare (size lhs, size RHS) {return Lo                Ng.signum (Lhs.getwidth () * Lhs.getheight ()-rhs.getwidth () * rhs.getheight ());        }            });    } return sizemap[0]; }

private void Setupimagereader () {//2 represents up to two frames of image stream in ImageReader Mimagereader = Imagereader.newinstance (mcaptu        Resize.getwidth (), Mcapturesize.getheight (), imageformat.jpeg, 1); Mimagereader.setonimageavailablelistener (New Imagereader.onimageavailablelistener () {@Override Publ                IC void onimageavailable (ImageReader reader) {final image image = Reader.acquirenextimage ();                Mcamerahandler.post (new Imagesaver (image));                        Getactivity (). Runonuithread (New Runnable () {@Override public void run () {                        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) {Ivshow.setimagebitmap (bitmap);            }                    }                });    }}, Mcamerahandler); }
public static class Imagesaver implements Runnable {private Image mimage;        Public Imagesaver (image image) {mimage = image;            } @Override public void Run () {Bytebuffer buffer = Mimage.getplanes () [0].getbuffer ();            byte[] data = new byte[buffer.capacity ()];            Buffer.get (data);            String path = environment.getexternalstoragedirectory () + "/dcim/361camera/";            File Mimagefile = new file (path);                if (!mimagefile.exists ()) {Boolean ret = Mimagefile.mkdirs ();            ASSERT (ret);            } String TimeStamp = new SimpleDateFormat ("Yyyymmdd_hhmmss"). Format (new Date ());            String fileName = path + "Img_" + TimeStamp + ". jpg";            FileOutputStream fos = null;                try {fos = new FileOutputStream (fileName);            Fos.write (data, 0, data.length); } catch (IOException e) {e.printstacktrace ();                    } finally {if (FOS! = null) {try {fos.close ();                    } catch (IOException e) {e.printstacktrace ();            }} mimage.close (); }        }    }
3. Turn on the camera

private void Opencamera () {        Mcameramanager = (Cameramanager) getcontext (). Getsystemservice (Context.camera_ SERVICE);        try {            if (activitycompat.checkselfpermission (GetContext (), Manifest.permission.CAMERA)! = packagemanager.permission_granted) {                //apply Write_external_storage permission                requestpermissions (New string[]{ Manifest.permission.CAMERA},                        request_camera_code);                return;            } else {                Mcameramanager.opencamera (mcameraid, Mstatecallback, Mcamerahandler);            }        } catch ( Cameraaccessexception e) {            e.printstacktrace ();        }    }

Implement the Statecallback interface, when the camera is opened will callback Onopened method, in this method to open the preview

Private Cameradevice.statecallback Mstatecallback = new Cameradevice.statecallback () {        @Override public        Void onopened (Cameradevice camera) {            mcameradevice = camera;            Startpreview ();        }        @Override public        void ondisconnected (Cameradevice camera) {            camera.close ();            Mcameradevice = null;        }        @Override public        void OnError (cameradevice camera, int error) {            camera.close ();            Mcameradevice = null;        }    };

4. Turn on camera preview

private void Startpreview () {surfacetexture msurfacetexture = Mtextureview.getsurfacetexture ();        Msurfacetexture.setdefaultbuffersize (Mpreviewsize.getwidth (), Mpreviewsize.getheight ());        Surface previewsurface = new Surface (msurfacetexture);            try {mcapturerequestbuilder = Mcameradevice.createcapturerequest (Cameradevice.template_preview);            Mcapturerequestbuilder.addtarget (Previewsurface); Mcameradevice.createcapturesession (Arrays.aslist (Previewsurface, Mimagereader.getsurface ()), new Cameracapturesession.statecallback () {@Override public void onconfigured (Cameracapturesessi                        on session) {try {mcapturerequest = Mcapturerequestbuilder.build ();                        Mcameracapturesession = session;                    Mcameracapturesession.setrepeatingrequest (mcapturerequest, NULL, Mcamerahandler);    } catch (Cameraaccessexception e) {                    E.printstacktrace ();                }} @Override public void onconfigurefailed (cameracapturesession session) {        }}, Mcamerahandler);        } catch (Cameraaccessexception e) {e.printstacktrace (); }    }

5, realize Previewcallback

First create a imagereader and listen to its events (see Code Setupimagereader () above). Then, before you turn on preview, set ImageReader to output your surface (see the code above Setupcamera ()).

6, taking pictures

public void Takepicture () {        lockfocus ();    }    private void Lockfocus () {        try {            mcapturerequestbuilder.set (Capturerequest.control_af_trigger, Camerametadata.control_af_trigger_start);            Mcameracapturesession.capture (Mcapturerequestbuilder.build (), Mcapturecallback, Mcamerahandler);        } catch (Cameraaccessexception e) {            e.printstacktrace ();        }    }

Source code address: Https://github.com/gengqifu/361Camera. Welcome to star a bit ~ ~ ~


Android Camera2 Photo (ii)--using Textureview

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.