Android example tutorial on using the camera class to write a mobile phone camera app _android

Source: Internet
Author: User

Camera is the camera class for Android camera hardware, located under the hardware package "Android.hardware.Camera". It is mainly used for camera capture pictures, start/stop preview pictures, take photos, get video frames, etc., it is the local service, responsible for managing the camera hardware on the device.

Camera since it is used to manage the camera hardware on the device, it also provides developers with the appropriate method, and most of these methods are native, with C + + at the bottom of the implementation, the following briefly describes some of the camera methods:

    • Static Camera open (): Opens Camera and returns a Camera instance.
    • static Camera open (int cameraid): Opens a Camera based on Cameraid and returns a Camera instance.
    • final void release (): Frees camera resources.
    • static int Getnumberofcameras (): Gets the number of camera hardware supported by the current device.
    • camera.parameters getparameters (): Gets the parameter settings class for Camera.
    • void Setparameters (camera.parameters params): writes Camera parameters to Camera by params.
    • final void setdisplayorientation (int degrees): the degree of rotation of the camera preview.
    • final void Setpreviewdisplay (Surfaceholder holder): Sets Surfaceholder for camera preview.
    • final void Starpreview (): Begins a preview of camera.
    • final void Stoppreview (): Stop Camera preview
    • final void Autofocus (Camera.autofocuscallback cb): AF.
    • Final takepicture (camera.shuttercallback shutter,camera.picturecallback raw,camera.picturecallback jpeg) Picture
    • final void Lock (): Locks the camera hardware so that other applications cannot be accessed.
    • final void unlock (): Unlocks the camera hardware so that other applications can be accessed.

This article has already introduced the common methods of camera, following these methods to explain in detail the basic process of using camera to develop photo application in Android:

    • Using the open () method to get a camera object, the open () method can open the specified camera via the camera ID, given that the Android device may have multiple cameras configured.
    • Sets the preview class for the camera object, which is a Surfaceholder object, set by the Setpreviewdisplay (Surfaceholder) method.
    • Call the Startpreview () method to begin a preview of the camera object.
    • The Takepicture () method is called to take a picture, where the image data is captured by the Camera.picturecallback () callback.
    • When the shot is complete, you need to call the Stoppreview () method to stop the preview and use release () to free the resources that camera occupies.

The steps described above are the most basic process and are essential. Camera does not provide a public constructor, it can only be obtained through the open () method, and a preview class Surfaceholder must be set, and camera cannot be used if it is not set. After you use the completion camera, you must use release () to free the camera resource.

instance:
use camera to control several steps for taking photos:
 1, calling camera open () opening camera
 2, calling camera getparameters () gets the camera parameters. This method returns a Camera.paremeters object
 3, invokes the Camera.parameters object method setting the parameters of the camera
 4, calling Camera.startpreview () method to begin previewing the view, you need to invoke the camera Setpreviewdisplay (Surfaceholder holder) method setting to use which surfaceview to display the framing picture before previewing the frame.
 5, call the camera Takepicture () method to take a picture
 6, end the program, call Camera () Stoppreview () End the view preview, and call the release () method to free the resource
&NBSP
Code:

<uses-permission android:name= "Android.permission.CAMERA"/> <relativelayout xmlns:android= "http://" Schemas.android.com/apk/res/android "xmlns:tools=" Http://schemas.android.com/tools "android:layout_width=" Match_ Parent "android:layout_height=" Match_parent "tools:context=". Mainactivity "> <surfaceview android:id=" @+id/sview "android:layout_width=" Match_parent "Andr" oid:layout_height= "Wrap_content"/> <button android:id= "@+id/take" tr 
    UE "android:onclick=" capture "android:layout_width=" Match_parent "android:layout_height=" Wrap_content " android:text= "@string/take"/> </RelativeLayout> <?xml version= "1.0" encoding= "Utf-8"?> <relativel Ayout xmlns:android= "http://schemas.android.com/apk/res/android" android:layout_width= "Match_parent" Android: layout_height= "Match_parent" > <edittext android:id= "@+id/photonmae" android:layouT_width= "Match_parent" android:layout_height= "wrap_content"/> <imageview android:id= "@+id/show" a ndroid:layout_below= "@id/photonmae" android:layout_width= "match_parent" android:layout_height= "Wrap_content"/&gt 
    
; 

 </RelativeLayout>
Package com.android.xiong.cameratest; 
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.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.Menu; 
Import Android.view.SurfaceHolder; 
Import Android.view.SurfaceHolder.Callback; 
Import Android.view.LayoutInflater; 
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 Mainactivity extends activity {Surfaceview Sview; 
  Surfaceholder Surfacehodler; 
  int screenwidth, screenheight; 
  Defines the camera Camera Camera used by the system; 
 
  Whether Boolean Ispreview = False exists in the preview; 
    @Override protected 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.activity_main); 
    Get window manager WindowManager WM = Getwindowmanager (); 
    Display display = Wm.getdefaultdisplay (); 
    Displaymetrics metrics = new Displaymetrics (); 
    Gets the width and height display.getmetrics (metrics) of the screen; 
    ScreenWidth = Metrics.widthpixels; 
    ScreenHeight = Metrics.heightpixels; 
    Sview = (Surfaceview) Findviewbyid (R.id.sview); Setting surface does not require its own maintenance cache Sview.getholder (). SetType (surfaceholder.surface_type_push_buffers); 
    To obtain Surfaceview surfaceholder Surfacehodler = Sview.getholder (); Add a callback listener for Srfaceholder Surfacehodler.addcallback (new Callback () {@Override public void surfacedes 
            Troyed (Surfaceholder arg0) {//If camera is not NULL, release camera if (camera!= null) {if (Ispreview) 
          Camera.stoppreview (); 
          Camera.release (); 
        camera = null; @Override public void surfacecreated (Surfaceholder arg0) {//Open camera Initcamer 
 
      A (); 
      @Override public void surfacechanged (Surfaceholder arg0, int arg1, int arg2, int arg3) { 
  } 
    }); private void Initcamera () {if (!ispreview) {///here defaults to open rear camera//The front camera can be opened via incoming parameters camera = 
      Camera.open (); 
    Camera.setdisplayorientation (90); } if (!ispreview && camera!= null) {Camera.parameters parameters = Camera.getparameters (); 
      Set the size of the preview photo parameters.setpreviewsize (screenwidth, screenheight); 
      Set the minimum and maximum number of frames displayed per second when previewing photos Parameters.setpreviewfpsrange (4, 10); 
      Set the format of the photo Parameters.setpictureformat (Imageformat.jpeg); 
      Set the quality of JPG photos parameters.set ("jpeg-quality", 85); 
      Set the size of the photo parameters.setpicturesize (ScreenWidth, screenheight); 
      Display the frame try {camera.setpreviewdisplay (Surfacehodler) by Surfaceview; 
      catch (IOException e) {//TODO auto-generated catch block E.printstacktrace (); 
      //Start preview Camera.startpreview (); 
    Ispreview = true; } public void Capture (View source) {if (camera!= null) {//Control camera autofocus before photographing camera.autofocus ( 
    Autofocuscallback); } autofocuscallback autofocuscallback = new Autofocuscallback () {@Override public void Onautofocus ( 
    Boolean arg0, Camera arg1) {  The IF (arg0) {//Takepicture () method needs to pass in three listening parameters//First listeners, fire the listener//second listener when the user presses the shutter, and fire the listener when the camera acquires the original photo 
          A third listener, which fires the listener camera.takepicture when the camera acquires a JPG photo (new Shuttercallback () {@Override public void Onshutter () {//press shutter moment to execute here Code}}, New Picturecallback () {@Ov  
        Erride public void Onpicturetaken (byte[] arg0, Camera arg1) {//Here the code can decide whether to save the original photo information} 
      }, Myjpegcallback); 
  } 
 
    } 
  }; Picturecallback myjpegcallback = new Picturecallback () {@Override public void Onpicturetaken (byte[) data, Cam ERA camera) {//Create a bitmap based on the data obtained from the photo final Bitmap BM = bitmapfactory.decodebytearray (data, 0, Data.leng 
      TH); 
      Load Layout file View Savedialog = Getlayoutinflater (). Inflate (r.layout.save, NULL); 
      Final EditText potoname = (edittext) savedialog. Findviewbyid (R.id.photonmae); Get savedThe ImageView component on the Ialog dialog box ImageView show = (ImageView) Savedialog.findviewbyid (r.id.show); 
      Show the photo just taken Show.setimagebitmap (BM); Use the Alertdialog component new Alertdialog.builder (Mainactivity.this). Setview (Savedialog). Setnegati 
                Vebutton ("Cancel", null). Setpositivebutton ("Save", new Dialoginterface.onclicklistener () { 
                  @Override public void OnClick (dialoginterface arg0, int arg1) { Create a file located on the SD card (environment. Getexternalstoragedirec Tory () + "/" + Potoname.gettext (). toString () + ". jpg" 
                  ); 
                  FileOutputStream Fileoutstream=null; 
                    try {fileoutstream=new fileoutputstream (file); Prints the bitmap to the specified file Bm.compress (compressformat.jpeg,Fileoutstream); 
                  Fileoutstream.close (); 
                  catch (IOException io) {io.printstacktrace (); 
      ). Show (); 
      Re-browse Camera.stoppreview (); 
      Camera.startpreview (); 
    Ispreview=true; 
 
  } 
  }; 
    @Override public boolean Oncreateoptionsmenu (Menu menu) {getmenuinflater (). Inflate (R.menu.main, menu); 
  return true; 

 } 
 
}

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.