Android Development Control Camera photo

Source: Internet
Author: User

today's phones generally provide camera functions, some cameras even support more than 13 million pixels, some even support independent focus, optical zoom these only SLR features, and even some mobile phones directly can be photographed stars. It can be said that the mobile phone has become a professional digital camera. To make the most of the camera features on the phone, the Android system provides a camera class to control the cameras. Now let's see if you use the camera class to control your phone taking pictures.  


Use Camera the steps to control your phone photo are as follows:

1) call the camera's open () method. 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.

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

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

4) call the camera's Startpreview () method to start previewing the framing and call the camera's Setpreviewdisplay (Surfaceholder holder) before previewing the framing method sets which surface View to use to display the framing photo.

5) call the camera's Takepicture () method to take a picture.

6) when the program is finished, call the camera's Stoppreview () to end the framing preview and call the release () method to release the resource.

Application Example: Auto focus when taking pictures  

The following example demonstrates using camera to take a picture, and when the user presses the camera key, the app automatically focuses and takes a photo when the focus is successful. The program's interface only provides a surfaceview to show preview framing, very simple. The program code is as follows:

Package Com.jph.camera;import Java.io.file;import Java.io.fileoutputstream;import java.io.ioexception;import Java.text.simpledateformat;import Java.util.date;import Java.util.locale;import Android.app.Activity;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;import android.widget.toast;/** * Control Mobile Camera * @author JPH * date:2014.08.20 * */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 of the Surfaceview component Sview = (Surfaceview) Findviewbyid (R.id.sview);//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;}} /** * This method is called in the layout file * */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); String Filename=getfilenmae (); if (filename==null) return;//creates a file that is located on the SD card files = new (FileName); 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 (); Toast.maketext (Captureimage.this, "photos to save to" +filename, Toast.length_short). Show (); catch (IOException e) {e.printstacktrace ();} Re-browse Camera.stoppreview (); Camera.startpreview (); Ispreview = true;}};/ * * Returns the file name of the ingest photo * @return file name * */protected String Getfilenmae () {//TODO auto-generated method stubstring filename;if (!e Nvironment.getexternalstoragestate (). Equals (environment.media_mounted)) {Toast.maketext (this, "monitor your phone without inserting an SD card, Please insert the SD card and try again ", Toast.length_long). Show (); return null;} SimpleDateFormat sdf=new SimpleDateFormat ("Yyyy-mm-dd HH.mm.ss", Locale.getdefault ()); filename= Environment.getexternalstoragedirectory () +file.separator+sdf.format (New Date ()) + ". JPG "; return fileName;}}


Program run:



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.