"Android" Custom camera implementation (continuous photo support, front and rear camera switching, continuous focus)

Source: Internet
Author: User

~ Reprint Please specify http://blog.csdn.net/u013015161/article/details/46921257

Introduced

These days, I wrote a demo of a custom camera that supports continuous photography and camera switching. Because I have not been exposed to the relevant programming, but also a learning process, here to do a record, but also to share, and attach the source code and engineering.
Effect

Switch the camera on the top left corner and take a picture on the right snap button.

General process

Android to take pictures, need to call camera class Android.hardware.Camera. To preview, you need to display a preview of each frame with Android.view.SurfaceView.
The general process for implementing a custom camera is:
1, with Addcallback to Surfaceview set callback interface object, the implementation of three callback methods: Surfacecreated, Surfacechanged, surfacedestroyed.
Open the camera in surfacecreated, get the camera object, and set it to preview on Surfaceview;
Set the camera parameters in the surfacechanged;
Release the camera at surfacedestroyed, otherwise it will cause the camera to not be called by other apps after exiting, including the system camera.
2, click the camera button, call the camera object's Takepicture method, its third parameter is the Picturecallback interface object, wherein the Onpicturetaken callback method parameter has a byte array, stored the captured picture data, Save to Local in the method.
In this way, a custom camera that is basically available with a preview is ready. But this is not enough, because there will be a variety of problems.

Main issues Preview Warp

This is the most troublesome problem. The first thing to know is the 3 aspect ratio: The camera resolution (picturesize) aspect ratio, the preview resolution (Previewsize) aspect ratio, and the aspect ratio of the surfaceview used as the preview. If you want the preview to not deform, the three aspect ratios need to be consistent. This consistency is maintained when the camera parameters are set. The code is as follows:

public void Setcameraanddisplay (int width, int height) {Camera. ParametersParameters = Camera. GetParameters();        / * Get a list of picturesize supported by the webcam * /List<camera. Size> picturesizelist = Parameters. getsupportedpicturesizes();        / * Select the appropriate resolution from the list * /Size picsize = camerautils. Getpropersize(Picturesizelist, ((float) width)/height);if (null! = picsize) {parameters. Setpicturesize(picsize. Width, picsize. Height);} else {picsize = parameters. Getpicturesize();}/ * Get a list of previewsize supported by the webcam * /List<camera. Size> previewsizelist = Parameters. getsupportedpreviewsizes();Size presize = camerautils. Getpropersize(Previewsizelist, ((float) width)/height);if (null! = presize) {Log. V("Testcameraactivitytag", presize. Width+","+ presize. Height);Parameters. Setpreviewsize(presize. Width, presize. Height);}/ * Reset the Surfaceview size according to the selected Picturesize * /float W = picsize. Width;Float h = picsize. Height;Surfaceview. Setlayoutparams(New Relativelayout. Layoutparams((int) (height* (w/h)), height)); Parameters. Setjpegquality( -);//Set photo qualityif (Parameters. Getsupportedfocusmodes(). Contains(Camera. Parameters. FOCUS_mode_continuous_picture)) {parameters. Setfocusmode(Camera. Parameters. FOCUS_mode_continuous_picture);} camera. Cancelautofocus();//Only with this sentence will the autofocus be automatically focused. Camera. Setdisplayorientation(0);Camera. Setparameters(parameters);}

Fangfali passed in the parameter is Surfaceview now the width of the height. In cases where the surfaceview aspect ratio is guaranteed to be constant (for example, to ensure full-screen preview), the respective picturesize and previewsize are searched for the qualifying conditions. If not, the picturesize and previewsize of the default aspect ratio (which I set to 4:3) are returned, and the aspect ratio of the Surfaceview is reset to ensure that the 3 aspect ratios are consistent.
The following classes are available for finding the appropriate picturesize and Previewsize methods:

 Public  class camerautils {     Public StaticSize Getpropersize (List<Size> sizelist, float displayratio) {//Sort the passed in size list firstCollections.sort (Sizelist,NewSizecomparator ()); Size result =NULL; for(Size size:sizelist) {Float Curratio = ((float) size.width)/size.height;if(Curratio-displayratio = =0{result = size; }        }if(NULL= = result) { for(Size size:sizelist) {Float Curratio = ((float) size.width)/size.height;if(Curratio = =3f/4{result = size; }            }        }returnResult }Static  class sizecomparator implements Comparator<Size> {@Override Publicint compare (size lhs, size RHS) {//TODO auto-generated method stubSize size1 = LHS; Size size2 = RHS;if(Size1.width < Size2.width | | size1.width = = Size2.width && size1.height < Size2.height) {return-1; }Else if(!            (Size1.width = = Size2.width && size1.height = = size2.height)) {return 1; }return 0; }    }}

Because different phones return the same sort of support resolution (in my hand a Lenovo from small to large sort, and another Nexus 4 from the big to the small sort), so we need to first order the list from small to large. This way, the method returns the maximum resolution that meets the conditional aspect ratio, which guarantees the sharpness of the photo.

Photo Orientation Error

The solution is to monitor changes in the direction of the phone. When the supervisor hears a change in direction, the imaging direction is reset by invoking the Setrotation method of the Camera.parameters object (the camera object calls the GetParameters () method).
The listener method is to set an object that implements the Orientationeventlistener interface in the activity and invoke its enable () method to activate.

IOrientationEventListener iOriListener;......iOriListener.enalbe();

Classes that implement the Orientationeventlistener interface:

 Public  class iorientationeventlistener extends orientationeventlistener{         Public Iorientationeventlistener(Context context) {Super(context);//TODO auto-generated constructor stub}@Override         Public void onorientationchanged(intOrientation) {//TODO auto-generated method stub            if(Orientation_unknown = = ORIENTATION) {return; } Camerainfo info =NewCamerainfo ();            Camera.getcamerainfo (camera_id, info); Orientation = (Orientation + $) / -* -;introtation =0;if(info.facing = = Camerainfo.camera_facing_front) {rotation = (info.orientation-orientation + the) % the; }Else{rotation = (info.orientation + orientation)% the; }if(NULL! = camera) {Camera.parameters Parameters = Camera.getparameters ();                Parameters.setrotation (rotation);            Camera.setparameters (parameters); }        }    }

The formula for setting rotation is provided by Google.

Preview Orientation Error

Because I set the camera's activity direction to Activityinfo.screen_orientation_landscape, that is, landscape mode, so I did not encounter this problem.
But in the last blog post I reproduced, there was a reference to the resolution of the relevant issues. The relevant code extracts, for everyone's reference. The following code is placed in the Surfaceview callback in the Surfacechanged method:

if(this.getResources().getConfiguration().orientation != Configuration.ORIENTATION_LANDSCAPE){//如果是竖屏parameters.set(“orientation”, “portrait”);//在2.2以上可以使用//camera.setDisplayOrientation(90);}else{parameters.set(“orientation”, “landscape”);//在2.2以上可以使用//camera.setDisplayOrientation(0);}
Continuous focus

With continuous focus, a clear picture can be taken. The code appears in the code snippet above.

/*先判断是否支持,否则可能报错*/        if (parameters.getSupportedFocusModes().contains(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE))        {            parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);        }        camera.cancelAutoFocus();//只有加上了这一句,才会自动对焦。  

The camera activity code is not all posted, more specific can refer to the demo project.

Project download

Click here to download the Custom Camera demo project

If the above sentence click Invalid, indicating that the resources are still audited ... Can go to Baidu cloud disk download:
Http://pan.baidu.com/s/1c077rDA.

Because I have the test model only two units, run the above demo friend convenient words can inform the running effect.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

"Android" Custom camera implementation (continuous photo support, front and rear camera switching, continuous focus)

Related Article

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.