Android Camera Camera

Source: Internet
Author: User

To take a photo with the camera step:

Call the camera's open () method to turn on the cameras. This method opens the rear-facing camera by default. If you need to turn on the specified camera, you can pass in the camera ID for that method.

Call the camera's GetParameters () method to get the camera parameters. The method returns a Camera.parameters object

Call the Camera.parameters object method to set the camera parameters

Call the camera's Startpreview () method to start previewing the framing and call the camera's Setpreviewdisplay (Surfaceholder holder) before previewing the framing Method set which Surfaceview to use to display the framing photo

Call camera's Takepicture () method to take a picture

When you end the program, call the camera's Stoppreview () to end the framing preview and call the release () method to release the resource


Instance code:

Activity:

Import Java.io.file;import java.io.fileoutputstream;import Java.io.ioexception;import Android.app.Activity;import Android.app.alertdialog;import Android.content.dialoginterface;import Android.content.dialoginterface.onclicklistener;import Android.graphics.bitmap;import Android.graphics.bitmap.compressformat;import Android.graphics.bitmapfactory;import Android.graphics.ImageFormat ; Import Android.hardware.camera;import Android.hardware.camera.autofocuscallback;import Android.hardware.camera.picturecallback;import Android.hardware.camera.shuttercallback;import Android.os.Bundle; Import Android.os.environment;import Android.util.displaymetrics;import Android.view.display;import Android.view.surfaceholder;import Android.view.surfaceholder.callback;import Android.view.SurfaceView;import Android.view.view;import Android.view.window;import Android.view.windowmanager;import Android.widget.EditText; Import Android.widget.imageview;public class Captureimage extends Activity{surfaceview Sview; SurfacEholder Surfaceholder;int ScreenWidth, screenheight;//defines whether camera camera;//used by the system is in preview Boolean ispreview = false;@ overridepublic void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);// Set Full screen requestwindowfeature (window.feature_no_title); GetWindow (). SetFlags (WindowManager.LayoutParams.FLAG_ Fullscreen,windowmanager.layoutparams.flag_fullscreen); Setcontentview (r.layout.main);//Get window manager WindowManager WM = Getwindowmanager ();D isplay Display = Wm.getdefaultdisplay ();D isplaymetrics metrics = new Displaymetrics ();// Gets the width and height of the screen display.getmetrics (metrics); screenwidth = Metrics.widthpixels;screenheight = metrics.heightpixels;// Gets the interface Surfaceview component Sview = (Surfaceview) Findviewbyid (R.id.sview);//Set the surface does not need to maintain its own buffer Sview.getholder (). SetType ( surfaceholder.surface_type_push_buffers);//Get Surfaceview Surfaceholdersurfaceholder = SView.getHolder ();// Add a callback listener for Surfaceholder Surfaceholder.addcallback (new Callback () {@Overridepublic void surfacechanged (Surfaceholder Holder, int format,iNT width, int height) {} @Overridepublic void surfacecreated (Surfaceholder holder) {//Open webcam Initcamera ();} @Overridepublic void surfacedestroyed (Surfaceholder holder) {//If the camera is not NULL, release the camera if (camera! = null) {if (Ispreview) Camera.stoppreview (); camera.release (); camera = null;}});} private void Initcamera () {if (!ispreview) {///Here the rear camera is turned on by default.  The front camera can be opened by passing in Parameters camera = camera.open (0); ①camera.setdisplayorientation (90);} if (camera! = null &&!ispreview) {try{camera.parameters Parameters = camera.getparameters ();// Set the size of the preview photo parameters.setpreviewsize (screenwidth, screenheight);// Sets the minimum and maximum number of frames per second to display when previewing a photo Parameters.setpreviewfpsrange (4, 10);//Set Picture format Parameters.setpictureformat (imageformat.jpeg )///Set the quality of the JPG photo parameters.set ("jpeg-quality", 85);//Set the size of the photo parameters.setpicturesize (ScreenWidth, screenheight);  /Display Framing Camera.setpreviewdisplay (surfaceholder) via Surfaceview;  ②//start previewing camera.startpreview (); ③}catch (Exception e) {e.printstacktrace ();} Ispreview = True;}} public void Capture (View soUrce) {if (camera! = NULL) {//Control camera autofocus before taking photos camera.autofocus (autofocuscallback); ④}}autofocuscallback autofocuscallback = new Autofocuscallback () {//When autofocus fires the method @overridepublic void Onautofocus ( Boolean success, Camera camera) {if (success) {///Takepicture () method requires incoming 3 listener parameters//1th listener: Fires the listener when the user presses the shutter// 2nd listener: Fires the Listener//3rd listener when the camera acquires the original photo: Fires the listener when the camera acquires a JPG photo camera.takepicture (new Shuttercallback () {public void Onshutter () {//press the shutter moment to execute this code}}, New Picturecallback () {public void Onpicturetaken (byte[] data, Camera c) {///Here The code can decide whether to save the original photo information}},  Myjpegcallback); ⑤}}}; Picturecallback myjpegcallback = new Picturecallback () {@Overridepublic void Onpicturetaken (byte[] data, camera camera) { Creates a bitmap based on the data taken from the camera final Bitmap BM = Bitmapfactory.decodebytearray (data, 0,data.length);//Load/layout/ Save.xml file corresponds to the layout resource View Savedialog = Getlayoutinflater (). Inflate (r.layout.save,null); final EditText photoname = ( EditText) Savedialog.findviewbyid (r.id.phone_name);//Get ImageView Component on Savedialog dialog box ImageView show = (ImageView) SavediaLog.findviewbyid (r.id.show);//Display the photos just taken show.setimagebitmap (BM);//Use the dialog box to display the Savedialog component new Alertdialog.builder ( captureimage.this). Setview (Savedialog). Setpositivebutton ("Save", new Onclicklistener () {@Overridepublic void OnClick ( Dialoginterface dialog, int which) {//Create a file located on the SD card files ' = ' new file ' (Environment.getexternalstoragedirectory (), Photoname.gettext (). toString () + ". jpg"); FileOutputStream OutStream = null;try{//Opens the output stream corresponding to the specified file OutStream = new FileOutputStream (file),//outputs the bitmap to the specified file Bm.compress ( Compressformat.jpeg, 100,outstream); Outstream.close ();} catch (IOException e) {e.printstacktrace ();}}}). Setnegativebutton ("Cancel", null). Show ();//re-browse Camera.stoppreview (); Camera.startpreview (); ispreview = true;}};}

Manifest file:

<!--grant the program permission to use the camera--><uses-permission android:name= "Android.permission.CAMERA"/> <uses-feature Android:name= "Android.hardware.camera"/> <uses-feature android:name= "Android.hardware.camera.autofocus"/ >


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.