Using Camera class in Android to write an example tutorial of mobile phone taking pictures of App

  • 2021-07-09 09:09:43
  • OfStack

Camera is the camera class of Android camera hardware, which is located under the hardware package "android. hardware. Camera". It is mainly used for camera to capture pictures, start/stop preview pictures, take pictures, obtain video frames, etc. It is a local service of the device and is responsible for managing the camera hardware on the device.

Since Camera is used to manage the camera hardware on the device, it also provides corresponding methods for developers, and most of these methods are native, which is implemented at the bottom with C + +. Here is a brief introduction to some methods of Camera:

static Camera open (): Open Camera and return 1 Camera instance. static Camera open (int cameraId): Open an Camera according to cameraId and return an Camera instance. final void release (): Releases Camera resources. static int getNumberOfCameras (): Gets the number of Camera hardware supported by the current device. Camera. Parameters getParameters (): Gets the various parameter setting classes for Camera. void setParameters (Camera. Parameters params): The parameters of Camera are written into Camera through params. final void setDisplayOrientation (int degrees): The rotation of the camera preview. final void setPreviewDisplay (SurfaceHolder holder): Sets the SurfaceHolder for the Camera preview. final void starPreview (): Begins a preview of Camera. final void stopPreview (): Stop preview of Camera final void autoFocus (Camera. AutoFocusCallback cb): Autofocus. final takePicture (Camera. ShutterCallback shutter, Camera. PictureCallback raw, Camera. PictureCallback jpeg): Take pictures. final void lock (): Locks Camera hardware so that other applications cannot access it. final void unlock (): Unlocks the Camera hardware so that other applications can access it.

The common methods of Camera have been introduced above. According to these methods, the following explains in detail the most basic process of developing photo application with Camera under Android:

Use the open () method to get an Camera object. Since the Android device may be configured with multiple cameras, the open () method can turn on the specified camera through the camera Id. Sets the preview class for the Camera object, which is an SurfaceHolder object set by the setPreviewDisplay (SurfaceHolder) method. Call the startPreview () method to start a preview of the Camera object. Call the takePicture () method to take a picture, where the captured Image data can be obtained through 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 occupied by Camera.

The steps described above are the most basic processes and are essential. Camera does not provide a exposed constructor and can only be obtained through the open () method, and a preview class SurfaceHolder must be set, without which Camera cannot be used. After using Camera, you must use release () to free Camera resources.

Example:
Use Camera to control several steps of taking pictures:
1. Call open () of Camera to turn on the camera
2. Call getParameters () of Camera to get photo parameters. This method returns 1 Camera. Paremeters object
3. Call the Camera. Parameters object method to set the parameters of taking pictures
4. Call Camera. startPreview () method to start previewing framing. Before previewing framing, you need to call setPreviewDisplay (SurfaceHolder holder) method of Camera to set which SurfaceView to use to display framing pictures.
5. Call the takePicture () method of Camera to take a picture
6. When the program is finished, call stopPreview () of Camera to finish framing preview, and call release () method to release resources

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" 
    android:layout_height="wrap_content"/> 
  <Button  
    android:id="@+id/take" 
    android:layout_alignParentBottom="true" 
    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"?> 
<RelativeLayout 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" 
    android:layout_below="@id/photoNmae" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content"/> 
    
</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; 
  //  Define the camera used by the system  
  Camera camera; 
  //  Is there in preview  
  boolean isPreview = false; 
 
  @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 the window manager  
    WindowManager wm = getWindowManager(); 
    Display display = wm.getDefaultDisplay(); 
    DisplayMetrics metrics = new DisplayMetrics(); 
    //  Gets the width and height of the screen  
    display.getMetrics(metrics); 
    screenWidth = metrics.widthPixels; 
    screenHeight = metrics.heightPixels; 
    sView = (SurfaceView) findViewById(R.id.sView); 
    //  Settings surface You don't need your own maintenance cache  
    sView.getHolder().setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); 
    //  Obtain SurfaceView Adj. SurfaceHolder 
    surfaceHodler = sView.getHolder(); 
    //  For srfaceHolder Add 1 Callback listeners  
    surfaceHodler.addCallback(new Callback() { 
 
      @Override 
      public void surfaceDestroyed(SurfaceHolder arg0) { 
        //  If camera Not for null , release the camera  
        if (camera != null) { 
          if (isPreview) 
            camera.stopPreview(); 
          camera.release(); 
          camera = null; 
        } 
      } 
 
      @Override 
      public void surfaceCreated(SurfaceHolder arg0) { 
        //  Turn on the camera  
        initCamera(); 
 
      } 
 
      @Override 
      public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, 
          int arg3) { 
      } 
    }); 
  } 
 
  private void initCamera() { 
    if (!isPreview) { 
      //  The rear camera is turned on by default here  
      //  You can turn on the front camera by passing in parameters  
      camera = Camera.open(); 
      camera.setDisplayOrientation(90); 
    } 
    if (!isPreview && camera != null) { 
      Camera.Parameters parameters = camera.getParameters(); 
      //  Set the size of preview photos  
      parameters.setPreviewSize(screenWidth, screenHeight); 
      //  Set the minimum and maximum values of how many frames per second to display when previewing photos  
      parameters.setPreviewFpsRange(4, 10); 
      //  Format photos  
      parameters.setPictureFormat(ImageFormat.JPEG); 
      //  Settings JPG The quality of photographs  
      parameters.set("jpeg-quality", 85); 
      //  Set the size of the photo  
      parameters.setPictureSize(screenWidth, screenHeight); 
      //  Pass SurfaceView Display framing screen  
      try { 
        camera.setPreviewDisplay(surfaceHodler); 
      } catch (IOException e) { 
        // TODO Auto-generated catch block 
        e.printStackTrace(); 
      } 
      //  Start previewing  
      camera.startPreview(); 
      isPreview = true; 
    } 
  } 
 
  public void capture(View source) { 
    if (camera != null) { 
      //  Control the camera to focus automatically before shooting  
      camera.autoFocus(autoFocusCallback); 
    } 
  } 
 
  AutoFocusCallback autoFocusCallback = new AutoFocusCallback() { 
 
    @Override 
    public void onAutoFocus(boolean arg0, Camera arg1) { 
      if (arg0) { 
        // takePicture() Method requires passing in 3 Listening parameters  
        //  No. 1 1 A listener; The listener is activated when the user presses the shutter  
        //  No. 1 2 A listener; Activate the listener when the camera takes the original photo  
        //  No. 1 3 A listener; When the camera acquires JPG Fire the listener when taking photos  
        camera.takePicture(new ShutterCallback() { 
 
          @Override 
          public void onShutter() { 
            //  The code here will be executed instantly when the shutter is pressed  
          } 
        }, new PictureCallback() { 
 
          @Override 
          public void onPictureTaken(byte[] arg0, Camera arg1) { 
            //  The code here can determine whether you need to save the original photo information  
          } 
        }, myJpegCallback); 
      } 
 
    } 
  }; 
  PictureCallback myJpegCallback = new PictureCallback() { 
 
    @Override 
    public void onPictureTaken(byte[] data, Camera camera) { 
      //  Create a bitmap based on the data obtained from taking photos  
      final Bitmap bm = BitmapFactory.decodeByteArray(data, 0, 
          data.length); 
      //  Load the layout file  
      View saveDialog = getLayoutInflater().inflate(R.layout.save, null); 
      final EditText potoName = (EditText) saveDialog 
          .findViewById(R.id.photoNmae); 
      //  Get saveDialog On the dialog box ImageView Component  
      ImageView show = (ImageView) saveDialog.findViewById(R.id.show); 
      //  Show the photos just taken  
      show.setImageBitmap(bm); 
      //  Use AlertDialog Component  
      new AlertDialog.Builder(MainActivity.this) 
          .setView(saveDialog) 
          .setNegativeButton(" Cancel ", null) 
          .setPositiveButton(" Save ", 
              new DialogInterface.OnClickListener() { 
                @Override 
                public void onClick(DialogInterface arg0, 
                    int arg1) { 
                  //  Create 1 Located in SD Files on the card  
                  File file = new File(Environment 
                      .getExternalStorageDirectory() 
                      + "/" 
                      + potoName.getText().toString() 
                      + ".jpg"); 
                  FileOutputStream fileOutStream=null; 
                  try { 
                    fileOutStream=new FileOutputStream(file); 
                    // Output the bitmap to the specified file  
                    bm.compress(CompressFormat.JPEG, 100, 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; 
  } 
 
} 


Related articles: