SoFunction
Updated on 2025-04-07

Android custom camera and analysis source code

Android custom camera and analysis source code

How to use Android system camera:

To make the application have a camera action, we must make some statements in the manifest file so that the system knows, as follows

 <intent-filter>
        <action android:name=".IMAGE_CAPTURE" />

        <category android:name="" />
      </intent-filter>

The function of action is to declare the type of action, which is easy to use intent, and the function of category is to register without it. The related operations will not work.
One way is to implement it simply and roughly, as follows

Intent intent=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    startActivityForResult(intent, REQ_1);
//Then the data acquisition is implemented in the onActivityResult method, which is displayed on an ImageViewif(resultCode==RESULT_OK){
      if(requestCode==REQ_1){
        Bundle bundle=();
        Bitmap bitmap=(Bitmap) ("data");
        (bitmap);
        }

A brief summary: This is a good thing, it is simple and fast, but in today's Android smartphones, many photos are very large, and what you get here is just a thumbnail

Another way is to be a little gentler, and the effect is better. The advantage is that it first stores the photo information in a local temporary file, and then lets the ImageView read it in the relevant path, so that the image with high definition can be obtained. as follows

/*
    * The meaning of this method is that it does not obtain the thumbnail of our photo in the data of the onActivityResult method, but directly view the original image from our file output directory.
    * This is the advantage of being able to operate large-capacity photos easily and accurately
    */
  public void onStartCarema2(View view){
    Intent intent=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    //See you passing the path back to your required processing method    Uri uri=(new File(myFilePath));
    //Set the output path of the file    (MediaStore.EXTRA_OUTPUT, uri);
    startActivityForResult(intent, REQ_2);
  }
// Then perform relevant processing in the onActivityResult methodelse if(requestCode==REQ_2){
        FileInputStream fis=null;
        try {
          fis=new FileInputStream(myFilePath);
          Bitmap bitmap=(fis);
          (bitmap);
        } catch (FileNotFoundException e) {
          // TODO Auto-generated catch block
          ();
        }finally{
          try {
            ();
          } catch (IOException e) {
            // TODO Auto-generated catch block
            ();
          }
        }
      }
    }
//Remember to close the relevant streaming operation at the end.  Otherwise, related exceptions will be caused.

Develop custom cameras

Since developing a custom camera requires the life of relevant permissions, you must not forget to do relevant processing in the manifest file, as follows

<uses-permission android:name=".WRITE_EXTERNAL_STORAGE"/>
  <uses-permission android:name=""/>

Then there are the following steps:

  • Create Camera, complete the initialization of Camera, start preview, and release resources three methods
  • Bind with the Activity's SurfaceView.
  • The system's onPause() and onResume() methods are set in the relevant state
  • The parameter setting of Camera is to set the photo type and status related to the photo
  • Displaying the photos taken will usually open a new Activity and use ImageView to host it. We can also add TextView to this Activity to achieve other beautification operations such as watermark effect.
  • In addition, if you want to add the autofocus function, you can add onClickListener() to the SurfaceView, listen to the screen, and call (null); method

The above is the whole idea

Next is the code display using the system Camera

(You can directly copy the relevant code blocks and add them to your application to implement the Camera function.)

First is MainActivity

layout

<LinearLayout xmlns:andro
  xmlns:tools="/tools"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:paddingBottom="@dimen/activity_vertical_margin"
  android:paddingLeft="@dimen/activity_horizontal_margin"
  android:paddingRight="@dimen/activity_horizontal_margin"
  android:paddingTop="@dimen/activity_vertical_margin"
  android:orientation="vertical"
  tools:context=".MainActivity" >

  <Button 
    android:
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="6dp"
    android:text="StartCarema"
    android:onClick="onStartCarema"
    />
  <Button 
    android:
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="6dp"
    android:text="StartCarema2"
    android:onClick="onStartCarema2"
    />
  <Button 
    android:
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="6dp"
    android:text="CustomCarema"
    android:onClick="onCustomCarema"
    />

  <ImageView 
    android:
    android:layout_width="match_parent"
    android:layout_height="match_parent"

    />

</LinearLayout>

Code

package ;

import ;
import ;
import ;
import ;

import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;

public class MainActivity extends Activity {
  // Used for the following acquisition request  private static int REQ_1=1;
  private static int REQ_2=2;

  Button btn_startCareme,btn_startCarema2,btn_customCarema;
  ImageView imageView;

  //Define the path to store the photo  private String myFilePath;
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    (savedInstanceState);
    setContentView(.activity_main);
    btn_startCareme=(Button) findViewById();
    btn_startCarema2=(Button) findViewById(.startCarema2);
    btn_customCarema=(Button) findViewById();
    imageView=(ImageView) findViewById();

    //Initialize the path of SD cards of different phones    myFilePath=().getPath();
    myFilePath=myFilePath+"/"+"";
  }

  public void onCustomCarema(View view){
    Intent intent=new Intent(this,);
    startActivity(intent);
  }

  public void onStartCarema(View view){
    Intent intent=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    startActivityForResult(intent, REQ_1);
  }

  /*
    * The meaning of this method is that it does not obtain the thumbnail of our photo in the data of the onActivityResult method, but directly view the original image from our file output directory.
    * This is the advantage of being able to operate large-capacity photos easily and accurately
    */
  public void onStartCarema2(View view){
    Intent intent=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    //See you passing the path back to your required processing method    Uri uri=(new File(myFilePath));
    //Set the output path of the file    (MediaStore.EXTRA_OUTPUT, uri);
    startActivityForResult(intent, REQ_2);
  }

  @Override
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // TODO Auto-generated method stub
    (requestCode, resultCode, data);
    if(resultCode==RESULT_OK){
      if(requestCode==REQ_1){
        Bundle bundle=();
        Bitmap bitmap=(Bitmap) ("data");
        (bitmap);
      }else if(requestCode==REQ_2){
        FileInputStream fis=null;
        try {
          fis=new FileInputStream(myFilePath);
          Bitmap bitmap=(fis);
          (bitmap);
        } catch (FileNotFoundException e) {
          // TODO Auto-generated catch block
          ();
        }finally{
          try {
            ();
          } catch (IOException e) {
            // TODO Auto-generated catch block
            ();
          }
        }
      }
    }
  }


}

Next is the code for customizing the camera

Main interface layout

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:andro
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:orientation="vertical" >

  <Button 
    android:
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="6dp"
    android:text="Capture"
    android:onClick="onCapture"
    />

  <SurfaceView 
    android:
    android:layout_width="match_parent"
    android:layout_height="match_parent"

    />



</LinearLayout>

ResultActivity layout

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:andro
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:orientation="vertical" >
  <TextView 
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Capture Result"
    android:textSize="28dp"
    android:textColor="#BFAACD"
    android:gravity="center"
    />  
    <ImageView 
      android:
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:scaleType="center"
      />

</LinearLayout>

Code

First is the CustomCamera class,

package ;

import ;
import ;
import ;
import ;

import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;

@SuppressWarnings("unused")
public class CustomCarema extends Activity implements {

  private Camera myCamera;

  private SurfaceView preview;
  private SurfaceHolder myHolder;  //myHolder is brave enough to display the image of the surfaceView
  private  myPictureCallBack=new () {

    @Override
    public void onPictureTaken(byte[] data, Camera arg1) {
      //Storage the data information obtained from taking photos to the local area      File tempFile=new File("/sdcard/");
      try {
        FileOutputStream fos=new FileOutputStream(tempFile);
        (data);
        ();
        //Then transfer the data information of this photo to the Activity to be displayed        Intent intent=new Intent(,);
        ("PicturePath", ());
        startActivity(intent);
        //After taking the photo, destroy the current activity and enter the picture display interface        ();
      } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        ();
      } catch (IOException e) {
        // TODO Auto-generated catch block
        ();
      }


    }
  };

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    (savedInstanceState);
    setContentView();
    preview=(SurfaceView) findViewById();
    myHolder=();
    (this);

    //Implement the function of auto-focusing on the screen. There is no need to take photos here, so it is just focus.    (new OnClickListener() {

      @Override
      public void onClick(View arg0) {
        // TODO Auto-generated method stub
        (null);
      }
    });
  }


  @Override
  protected void onResume() {
    ();
    if(myCamera==null){
      myCamera=getCamera();
      if(myHolder != null ){
        setStartPreview(myCamera, myHolder);
      }
    }
  }

  @Override
  protected void onPause() {
    // TODO Auto-generated method stub
    ();
    releaseCamera();
  }

  /**
    * Free up the camera resources
    */
  private void releaseCamera(){
    if(myCamera !=null ){
      (null);
      ();
      ();
      myCamera=null;
    }
  }


  /**
    * Some parameters for taking pictures. Clicking this button will trigger the photo to drop, thereby achieving the effect of taking pictures.
    * @param view
    */
  public void onCapture(View view){
     parameters=();
    //Set the photo type    ();
    (800, 600);
    //Set to autofocus    (.FOCUS_MODE_AUTO);
    //Setting it to autofocus is not enough, because we first get the clearest picture, so we must take photos when the focus is successful    (new () {

      @Override
      public void onAutoFocus(boolean success, Camera camera) {
        // TODO Auto-generated method stub
        if(success){
          (null, null, myPictureCallBack);
        }
      }
    });
  }

  /**
    * Get a Camera object of the system
    */
  private Camera getCamera(){
    Camera camera=null;
    try{
      camera=();
    }catch(Exception e){
      ();
    }

    return camera;
  }

  /**
    * Start previewing the content of the camera, which is actually about binding the surfaceHolder to it.
    */
  private void setStartPreview(Camera camera,SurfaceHolder holder){
    //Directly call the system method to bind preview    try {
      (holder);
      //Since the system uses landscape preview by default, so you need to set it up      (90);
      ();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      ();
    }

  }




  @Override
  public void surfaceChanged(SurfaceHolder holder, int arg1, int arg2, int arg3) {
    // TODO Auto-generated method stub
    ();
    setStartPreview(myCamera, myHolder);
  }


  @Override
  public void surfaceCreated(SurfaceHolder holder) {
    // TODO Auto-generated method stub
    setStartPreview(myCamera, myHolder);
  }


  @Override
  public void surfaceDestroyed(SurfaceHolder arg0) {
    // TODO Auto-generated method stub
    releaseCamera();
  }

}

Then the result interface code:

package ;

import ;
import ;

import ;
import ;
import ;
import ;
import ;
import ;

public class ResultActivity extends Activity {

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    (savedInstanceState);
    setContentView();
    String path=getIntent().getStringExtra("PicturePath");
    ImageView imageview=(ImageView) findViewById();
    //Because we get horizontal screen so immaturely, we need to use the form of stream to convert//   Bitmap bitmap=(path);
//   (bitmap);
    FileInputStream fis;
    try {
      fis = new FileInputStream(path);
      Bitmap bitmap=(fis);
      Matrix matrix=new Matrix();
      (90);
      bitmap=(bitmap, 0,0, ()
          ,(),matrix,true);
      (bitmap);
    } catch (FileNotFoundException e) {
      // TODO Auto-generated catch block
      ();
    }


  }
}

The code comments for the lower level have been made in the above code

Summarize:

Remember to add dynamic permissions on Android 6.0 or above, otherwise the empty pointer will be reported. There is also a click to take a photo event. Don’t forget to add it, otherwise there will be no response to taking photos.

The above is a detailed explanation of the examples of Android custom cameras. If you have any questions, please leave a message or go to the community of this site to communicate and discuss. Thank you for reading. I hope it can help you. Thank you for your support for this site!