Android Camera Development Detailed

Source: Internet
Author: User

There are two general types of camera features used in Android: one is to call the system camera directly, one to write your own camera.
I'll show you two ways to use each:
The first: is to use intent to jump to the system camera, action: Android.media.action.STILL_IMAGE_CAMERA
Key code:

Intent Intent = new Intent (); Call  the camera intent.setaction ("Android.media.action.STILL_IMAGE_CAMERA");   

Want to test, you can create a new project directly, and the main activity of the code to replace the above, and then run, I tested it, the above code does not require permissions, after all, just call the system comes with the program. Of course, there are some other related calling methods on the Internet, as long as the action is set, then the system will call the system's own camera.

The second type:

(1) First we have to create a photo ourselves, we must consider what controls to display the camera preview effect, obviously Android has helped us to make a choice, that is
Surfaceview, while the control Surfaceview requires a surfaceholder, which is a system-provided object that is used to set the Surfaceview, which is obtained by means of the Surfaceview.getholder (). And the camera provides a setpreviewdisplay (Surfaceholder) way to connect
Surfaceholder, and through him to control the Surfaceview, and we use the Android camera class to provide Startpreview () and Stoppreview () to turn preview on and off.
The relationship is as follows:
Camera---->surfaceholder------>surfaceview.


(2) Know how to preview, of course, also know how to turn on the camera. Camera.open () This is a static method, if the camera is not used by others, it will return a camera reference, if the person is used, it will throw an exception. Strangely enough, this method can not be placed casually, such as in the construction method or OnCreate () method, will be taken as no preview effect.


(3)
Surfaceholder.callback, which is an interface holder used to display surfaceview data, he must implement 3 different methods
Surfacecreated () This method is called after surface is created.
Surfacechanged () This method is called when the Surfaceview has changed
Surfacedestroyed () This is called when the Surfaceview is destroyed.
Surfaceholde binds the interface of the response to him through the Addcallback () method.
Surfaceholder must also set a Settype () method, when viewing the API, found that this method is outdated, but did not write, and will error. All sorts of strange.


(4)
I used the above knowledge to write a Mysurfaceview class, he inherited from the Surfaceview, and in the inside realized the camera preview function. I think the simplest camera preview code:
Mysurfaceview.java

Import java.io.IOException;       public class Mysurfaceview extends Surfaceview implements surfaceholder.callback{Surfaceholder holder;      Camera Mycamera;           Public Mysurfaceview (Context context) {super (context);           Holder = Getholder ();//Get Surfaceholder reference holder.addcallback (this); Holder.settype (surfaceholder.surface_type_push_buffers);//set type} @Override public void surfacechanged (S              Urfaceholder holder, int format, int width, int height) {mycamera.startpreview ();           } @Override public void surfacecreated (Surfaceholder holder) {//TODO auto-generated method stub               if (Mycamera = = null) {Mycamera = Camera.open ();//Turn on the camera and not in the constructor, otherwise the screen will not be displayed.               try {mycamera.setpreviewdisplay (holder); } catch (IOException e) {//TODO auto-generated catch block E.printstacktrace ();              }}} @Override public void surfacedestroyed (Surfaceholder holder) {           TODO auto-generated Method Stub Mycamera.stoppreview ();//Stop preview mycamera.release ();//Release camera resources           Mycamera = null;        LOG.D ("ddd", "4"); }   }

And you must add permissions to the app: <uses-permission android:name= "Android.permission.CAMERA" ></uses-permission>

(5) Can preview, followed by the photo, took a picture of a camera.tackpiture () This method, this method, there are three parameters are
Shuttercallback shutter,picturecallback raw,picturecallback jpeg.
Here are the implementations for them

Private Shuttercallback shutter = new Shuttercallback () {              @Override public       void Onshutter () {           //TODO Auto-ge nerated method Stub          log.d ("ddd", "shutter");               }   ;   Private Picturecallback raw = new Picturecallback () {              @Override public       void Onpicturetaken (byte[] data, Camera CA Mera) {           //TODO auto-generated method stub           log.d ("ddd", "raw");                }  };   Private Picturecallback jpeg = new Picturecallback () {      @Override public      void Onpicturetaken (byte[] data, Camera camera) {           //TODO auto-generated method stub          log.d ("ddd", "jpeg");       }  };  

When the photo is started, the shutter Onshutter () method, raw Onpicturetaken method, and the Onpicturetaken method of the JPEG are called in turn. The function of the
three parameters is shutter--to take a picture of the instant call, raw--get uncompressed picture data, JPEG---return JPEG image data
When you do not need to process the photos, you can use NULL instead.
Note that when the Camera.takepiture method is called, the camera closes the preview, and you need to call Startpreview () to turn the preview back on.

I use the above knowledge to add to the above example, the following code is formed:

Package Com.wjh.camera;  Import java.io.IOException;   Import Android.content.Context;      .... public class Mysurfaceview extends Surfaceview implements surfaceholder.callback{Surfaceholder holder;       Camera Mycamera;               Private Shuttercallback shutter = new Shuttercallback () {@Override public void Onshutter () {           TODO auto-generated Method Stub log.d ("ddd", "shutter");       }      };  Private Picturecallback raw = new Picturecallback () {@Override public void Onpicturetaken (byte[] data,                         Camera camera) {//TODO auto-generated Method Stub log.d ("DDD", "raw");       }      }; Private Picturecallback jpeg = new Picturecallback () {@Override public void Onpicturetaken (byte[] data, camera camera)                          {//TODO auto-generated Method Stub log.d ("DDD", "jpeg");       }       };Public Mysurfaceview (Context context) {super (context);           Holder = Getholder ();//Get Surfaceholder reference holder.addcallback (this); Holder.settype (surfaceholder.surface_type_push_buffers);//set type} public void Tackpicture () {m       Ycamera.takepicture (Null,null,null);       } public void Voertack () {Mycamera.startpreview (); } @Override public void surfacechanged (surfaceholder holder, int format, int width, int height) {MyC              Amera.startpreview ();           } @Override public void surfacecreated (Surfaceholder holder) {//TODO auto-generated method stub               if (Mycamera = = null) {Mycamera = Camera.open ();//Turn on the camera and not in the constructor, otherwise the screen will not be displayed.               try {mycamera.setpreviewdisplay (holder); } catch (IOException e) {//TODO auto-generated catch block E.printstacktrace (); }}} @Override public void surfacedestroyed (Surfaceholder holder) {//TODO  auto-generated method Stub Mycamera.stoppreview ();//Stop preview mycamera.release ();//Release camera Resources Mycamera       = NULL; }   }

Cameratest_3.java

Import android.app.Activity;  ... import Android.view.View.OnClickListener;   public class Cameratest_3 extends activity implements Onclicklistener  {       /** called when the activity is first Crea Ted. */       Mysurfaceview mysurface;      Boolean isclicked = false;       @Override public       void OnCreate (Bundle savedinstancestate) {           super.oncreate (savedinstancestate);           Mysurface = new Mysurfaceview (this);          Setcontentview (mysurface);          Mysurface.setonclicklistener (this);       }       @Override public      void OnClick (View v) {           //TODO auto-generated method Stub           if (!isclicked)           {          Mysurface.tackpicture ();           Isclicked = true;           } else           {               mysurface.voertack ();              isclicked = false;          }            }  

This is the realization of the function of the camera, then how to save the picture? So this is what you need to do with the JPEG
method in that parameter, which is the data parameter of the photo.
We get the picture via Bitmapfactory.decodebytearray (data, 0, data.length) and save the picture to the location we want to save by IO processing, save the photo to/sdcard/ Wjh.jpg, and delete some unused code, leaving some code that is necessary

Package Com.wjh.camera;   Import Java.io.BufferedInputStream;   Import Java.io.BufferedOutputStream;       ... public class Mysurfaceview extends Surfaceview implements surfaceholder.callback{Surfaceholder holder;       Camera Mycamera; Private Picturecallback jpeg = new Picturecallback () {@Override public void Onpicturetaken (byte[] data, Camera camera) {//TODO auto-generated Method stub try {Bitma                   P BM = Bitmapfactory.decodebytearray (data, 0, data.length);                   File File = new file ("/sdcard/wjh.jpg");                   Bufferedoutputstream BOS = new Bufferedoutputstream (new FileOutputStream (file));                   Bm.compress (Bitmap.compressformat.jpeg,100,bos);                   Bos.flush ();              Bos.close ();               }catch (Exception e) {e.printstacktrace ();       }           }       }; Public Mysurfaceview (ContextContext) {super (context);           Holder = Getholder ();//Get Surfaceholder reference holder.addcallback (this);           Holder.settype (surfaceholder.surface_type_push_buffers);//set type} public void Tackpicture () {       Mycamera.takepicture (Null,null,jpeg);     } public void Voertack () {Mycamera.startpreview (); } @Override public void surfacechanged (surfaceholder holder, int format, int width, int height) {MyC             Amera.startpreview ();           } @Override public void surfacecreated (Surfaceholder holder) {//TODO auto-generated method stub               if (Mycamera = = null) {Mycamera = Camera.open ();//Turn on the camera and not in the constructor, otherwise the screen will not be displayed.              try {mycamera.setpreviewdisplay (holder);               } catch (IOException e) {//TODO auto-generated catch block E.printstacktrace ();    }           }          } @Override public void surfacedestroyed (Surfaceholder holder) {//TODO auto-generated Me       Thod stub Mycamera.stoppreview ();//Stop preview mycamera.release ();//Release camera resource mycamera = NULL;   }  }

Cameratest_3.java is the same as above
Note that this is a privilege that must be added on the SD card to write data
<uses-permission android:name= " Android.permission.WRITE_EXTERNAL_STORAGE "/>

(7) to take a picture, it's a good thing to think about how to make it look better, which is obviously a professional strength, but we can do some processing on the program,
to those above, because I directly put Surfaceview as the overall layout, it may appear that the screen has been opened, not very good-looking, so at this point, you can not put
Surfaceview into the overall layout, put him into a layout manager, in setting the relevant parameters.

It is important to note that some parameters cannot be arbitrarily set,
such as the following code: Camera.parameters parames = Mycamera.getparameters ();//Get Parameter Object
Parames.setpictureformat (pixelformat.jpeg);//Set the picture format
Parames.setpreviewsize (640,480);//This parameter can only be a few specific parameters, Otherwise you will get an error. (176*144,320*240,352*288,480*360,640*480)
Mycamera.setparameters (parames);

There are auto-focus, of course, some phones do not have this function, autofocus is through autofocus () This method calls an autofocus interface, and processing inside.
Note that this method must be in the middle of Startpreview () and Stoppreview ().
Autofocuscallback is an auto-focus interface that implements the public void Onautofocus (Boolean success, Camera camera) method,
So we can put the photo method in here, then focus and then shoot. The effect will be much better.

Note that autofocus needs to be added <uses-feature android:name= "Android.hardware.camera.autofocus"/>
below I call directly the above use example to write directly.
Cameratest_4.java

Import Java.io.BufferedOutputStream;   Import Java.io.File;  Import Java.io.FileOutputStream;   Import java.io.IOException;   Import android.app.Activity;   Import Android.content.pm.ActivityInfo;   Import Android.graphics.Bitmap;   Import Android.graphics.BitmapFactory;   Import Android.graphics.PixelFormat;   Import Android.hardware.Camera;  Import Android.hardware.Camera.AutoFocusCallback;  Import Android.hardware.Camera.PictureCallback;  Import Android.os.Bundle;   Import Android.view.SurfaceHolder;   Import Android.view.SurfaceView;   Import Android.view.View;   Import Android.view.Window;   Import Android.view.SurfaceHolder.Callback;   Import Android.view.View.OnClickListener; public class Cameratest_4 extends Activity implements Callback, Onclicklistener, autofocuscallback{Surfaceview mysu Rfaceview;//surfaceview Statement Surfaceholder holder;//surfaceholder statement camera mycamera;//camera declares String filepath= " /sdcard/wjh.jpg ";//Photo save path Boolean isclicked = false;//whetherClick logo//create JPEG image callback data object Picturecallback JPEG = new Picturecallback () {@Override PU               Blic void Onpicturetaken (byte[] data, Camera camera) {//TODO auto-generated Method stub try               {//Get picture Bitmap BM = Bitmapfactory.decodebytearray (data, 0, data.length);               File File = new file (FilePath);               Bufferedoutputstream BOS = new Bufferedoutputstream (new FileOutputStream (file));                Bm.compress (Bitmap.CompressFormat.JPEG, N, Bos);//compress the picture into the stream Bos.flush ();//output Bos.close ();//Close              }catch (Exception e) {e.printstacktrace ();      }         }       }; /** called when the activity is first created.           */@Override public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);                    Requestwindowfeature (window.feature_no_title);//Untitled Set shooting Direction this.setrequestedorientation (Activityinfo.screen_orientation_landscape);           Setcontentview (R.layout.main);           Get Control Mysurfaceview = (Surfaceview) Findviewbyid (R.ID.SURFACEVIEW1);           Get Handle holder = Mysurfaceview.getholder ();           Add callback Holder.addcallback (this);           Set type Holder.settype (Surfaceholder.surface_type_push_buffers);      Set the monitoring Mysurfaceview.setonclicklistener (this); } @Override public void surfacechanged (surfaceholder holder, int format, int width, int height) {//T           ODO auto-generated Method Stub//Set parameters and start previewing camera.parameters params = Mycamera.getparameters ();           Params.setpictureformat (Pixelformat.jpeg);           Params.setpreviewsize (640,480);           Mycamera.setparameters (params);                 Mycamera.startpreview ();      } @Override public void surfacecreated (Surfaceholder holder) {    TODO auto-generated Method Stub//Turn on camera if (Mycamera = = null) {Mycamera =               Camera.open ();              try {mycamera.setpreviewdisplay (holder);               } catch (IOException e) {//TODO auto-generated catch block E.printstacktrace ();           }}} @Override public void surfacedestroyed (Surfaceholder holder) {          TODO auto-generated Method Stub//close Preview and Release Resource Mycamera.stoppreview ();           Mycamera.release ();               Mycamera = null;          } @Override public void OnClick (View v) {//TODO auto-generated Method stub if (!isclicked)           {Mycamera.autofocus (this);//AF isclicked = true;          }else {Mycamera.startpreview ();//Open Preview isclicked = false; }} @Override PubLIC void Onautofocus (Boolean success, Camera camera) {//TODO auto-generated Method stub if (success)               {//Set parameters and take photos camera.parameters params = mycamera.getparameters ();               Params.setpictureformat (Pixelformat.jpeg);               Params.setpreviewsize (640,480);               Mycamera.setparameters (params);           Mycamera.takepicture (NULL, NULL, JPEG); }           }   }

Androidmanifest.xml

<?xml version= "1.0" encoding= "Utf-8"? ><manifest xmlns:android= "http://schemas.android.com/apk/res/ Android "package=" Com.wjh.camera "android:versioncode=" 1 "android:versionname=" 1.0 "> <uses-sdk A ndroid:minsdkversion= "7"/> <uses-permission android:name= "Android.permission.CAMERA" ></ uses-permission> <uses-feature android:name= "Android.hardware.camera.autofocus"/> <uses-permission Android:name= "Android.permission.WRITE_EXTERNAL_STORAGE"/> <application android:icon= "@drawable/icon" Android:label= "@string/app_name" > <activity android:name= ". Cameratest_4 "android:label=" @string/app_name "> <intent-filter> < Action android:name= "Android.intent.action.MAIN"/> <category android:name= "android.intent.category. LAUNCHER "/> </intent-filter> </activity> </application> </manifest>

Main.xml

<linearlayout xmlns:android= "http://schemas.android.com/apk/res/android"     androidrientation= "vertical"       android:layout_width= "fill_parent"       android:layout_height= "fill_parent"       >       <surfaceview Android:id= "@+id/surfaceview1"     android:layout_width= "640px"        android:layout_height= "480px"        android: layout_gravity= "Center" >

  

Android Camera Development Detailed

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.