Camera Control for Android Development

Source: Internet
Author: User

Camera Control for Android Development

Currently, mobile phones generally provide camera functions. Some cameras even support more than 13 million pixels, and some even support independent focus and optical zoom. These functions are available only for slrs, even some mobile phones can be directly advertised to capture stars. It can be said that mobile phones have become professional digital cameras. To make full use of Camera functions on mobile phones, the Android system provides the Camera class to control Camera photos. Now let's take a look at how to use the Camera class to control mobile phone photos.


Follow these steps to take a photo using the Camera mobile phone:

1) Call the open () method of Camera to open the Camera. This method enables the rear camera by default. If you need to enable the specified camera, you can pass in the camera ID for this method.

2) Call the getParameters () method of Camera to obtain the Camera parameters. This method returns a Camera. Parameters object.

3) Call the Camera. Parameters object method to set the Camera Parameters.

4) Call the startPreview () method of Camera to start previewing the scene. before previewing the scene, call the setPreviewDisplay (SurfaceHolder holder) method of Camera to set which Surface View is used to display the photo.

5) Call the takePicture () method of Camera to take a photo.

6) when the program ends, call the stopPreview () method of Camera to end the scenario preview and call the release () method to release the resource.

Application Example: auto focus when taking a photo

The following example demonstrates how to use Camera to take a photo. When a user presses the photo key, the app will automatically focus and take a photo when the focus is successful. Only one SurfaceView is provided on the Interface of this program to display the preview view, which is 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 Droid. 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 phone photo ** @ author jph * Date: 2014.08.20 **/public class CaptureImage extends Activity {SurfaceView sView; SurfaceHolder surfaceHolder; int screenWidth, screenHeight; // define the Camera camera Camera used by the system; // boolean isPreview = false in preview; @ Overridepublic void onCreate (Bu Ndle savedInstanceState) {super. onCreate (savedInstanceState); // sets the full screen requestWindowFeature (Window. FEATURE_NO_TITLE); getWindow (). setFlags (WindowManager. layoutParams. FLAG_FULLSCREEN, WindowManager. layoutParams. FLAG_FULLSCREEN); setContentView (R. layout. main); // obtain the window manager WindowManager wm = getWindowManager (); Display display = wm. getdefadisplay display (); DisplayMetrics metrics = new DisplayMetrics (); // get the screen width and height dis Play. getMetrics (metrics); screenWidth = metrics. widthPixels; screenHeight = metrics. heightPixels; // obtain the SurfaceView component sView = (SurfaceView) findViewById (R. id. sView); // obtain SurfaceHoldersurfaceHolder = sView of SurfaceView. getHolder (); // Add a callback listener surfaceHolder for surfaceHolder. addCallback (new Callback () {@ Overridepublic void surfaceChanged (SurfaceHolder holder, int format, int width, int height) {}@ Overridepubl Ic void surfaceCreated (SurfaceHolder holder) {// enable camera initCamera () ;}@ Overridepublic void surfaceDestroyed (SurfaceHolder holder) {// if camera is not null, release the camera if (camera! = Null) {if (isPreview) camera. stopPreview (); camera. release (); camera = null ;}});} private void initCamera () {if (! IsPreview) {// The rear camera is enabled by default. // You can enable the front camera Camera = camera. open (0); // ① camera. setDisplayOrientation (90);} if (camera! = Null &&! IsPreview) {try {Camera. parameters parameters = camera. getParameters (); // set the size of the previewed photo parameters. setPreviewSize (screenWidth, screenHeight); // sets the minimum and maximum parameters values of the number of frames displayed per second during preview. setPreviewFpsRange (4, 10); // set the image format parameters. setPictureFormat (ImageFormat. JPEG); // set the quality of the JPG photo parameters. set ("jpeg-quality", 85); // set the Photo size parameters. setPictureSize (screenWidth, screenHeight); // use SurfaceView to display the camera image. setPreview Display (surfaceHolder); // ② // 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) {// controls the camera to focus automatically before taking a photo of camera. autoFocus (autoFocusCallback); // ④} AutoFocusCallback autoFocusCallback = new AutoFocusCallback () {// This method is triggered when auto focus is enabled @ Overridepublic void onAutoFocus (boolean success, Camera camera) {if (success) {// The takePicture () method needs to input three listener parameters // 1st listeners: The Listener is triggered when the user presses the shutter: // 2nd listeners: this listener is triggered when the camera gets the original photo // 3rd listeners: This listener is triggered when the camera gets the JPG image. camera. takePicture (new ShutterCallback () {public void onShutter () {// when the shutter is pressed Run code }}, new PictureCallback () {public void onPictureTaken (byte [] data, Camera c) {// The code here determines whether to save original photo information }}, my‑callback); // ⑤ }}; PictureCallback my‑callback = new PictureCallback () {@ Overridepublic void onPictureTaken (byte [] data, Camera camera) {// create a Bitmap final Bitmap bm = BitmapFactory based on the data obtained from the image. decodeByteArray (data, 0, data. length); String fileName = getFileNmae (); if (fileName = null) return; // create File files on the SD card = new file (fileName); FileOutputStream outStream = null; try {// open the output stream outStream = new FileOutputStream (File) corresponding to the specified file ); // output the bitmap to the specified object bm. compress (CompressFormat. JPEG, 100, outStream); outStream. close (); Toast. makeText (CaptureImage. this, "Save the photo to" + fileName, Toast. LENGTH_SHORT ). show ();} catch (IOException e) {e. printStackTrace ();} // browse camera again. stopPreview (); camera. startPreview (); isPreview = t Rue ;}};/***** return the file name of the photo to be taken * @ return file name **/protected String getFileNmae () {// TODO Auto-generated method stubString fileName; if (! Environment. getExternalStorageState (). equals (Environment. MEDIA_MOUNTED) {Toast. makeText (this, "No SD card is detected on your mobile phone. 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 running:



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.