Easy Tutorial
❮ Java Transient Keywords Linux Check Port Usage ❯

9.3 Using Camera to Take Photos

Category Android Basic Tutorial

Introduction to This Section

This section introduces the use of Camera in Android, simply put, it's about taking photos, which can be done in two ways:

  1. Call the system's built-in camera to take a photo and then obtain the image after the photo is taken.

  2. Or write your own photo-taking page.

In this section, we will write two simple examples to experience the above two scenarios~


1. Calling the System's Built-in Camera

We only need the following line of code to call the system camera, and after the camera takes a photo, it will return an intent to onActivityResult. The extra part of the intent contains an encoded Bitmap~

Intent it = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(it, Activity.DEFAULT_KEYS_DIALER);

// Override the onActivityResult method
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if(requestCode == Activity.RESULT_OK){
        Bundle bundle = data.getExtras();
        Bitmap bitmap = (Bitmap) bundle.get("data");
        img_show.setImageBitmap(bitmap);
    }
}

Running Effect Picture :

This blurry AV quality... After all, it's an encoded Bitmap. By the way, the photo taken will not be saved locally. We can write our own code to save the photo to our SD card, and then display it, which will be much clearer. Well, let's try it with code~

// Define a File variable for saving the image
private File currentImageFile = null;

// Write these things at the button click event, which is to create an image file on the SD card:
@Override
public void onClick(View v) {
    File dir = new File(Environment.getExternalStorageDirectory(),"pictures");
    if(dir.exists()){
        dir.mkdirs();
    }
    currentImageFile = new File(dir,System.currentTimeMillis() + ".jpg");
    if(!currentImageFile.exists()){
        try {
            currentImageFile.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    Intent it = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    it.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(currentImageFile));
    startActivityForResult(it, Activity.DEFAULT_KEYS_DIALER);
}

//onActivityResult:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == Activity.DEFAULT_KEYS_DIALER) {
        img_show.setImageURI(Uri.fromFile(currentImageFile));
    }
}

Well, it's very simple, let's look at the running result:

Much clearer than the one above~ Calling the system's built-in Camera is just that simple~


2. Write Your Own Photo-Taking Page

Here we need to use a SurfaceView as our preview interface, which is very simple to use!

Running Effect Picture :

Code Implementation :

Layout code: activity_main.xml : A simple surfaceView + Button

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <SurfaceView
        android:id="@+id/sfv_preview"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1" />

    <Button
        android:id="@+id/btn_take"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Call System Camera" />

</LinearLayout>

MainActivity.java :

public class MainActivity extends AppCompatActivity {

    private SurfaceView sfv_preview;
    private Button btn_take;
    private Camera camera = null;
    private SurfaceHolder.Callback cpHolderCallback = new SurfaceHolder.Callback() {
        @Override
        public void surfaceCreated(SurfaceHolder holder) {
            startPreview();
        }

        @Override
        public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

        }

        @Override
        public void surfaceDestroyed(SurfaceHolder holder) {
            stopPreview();
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        bindViews();
    }

    private void bindViews() {
        sfv_preview = (SurfaceView) findViewById(R.id.sfv_preview);
        btn_take = (Button) findViewById(R.id.btn_take);
        sfv_preview.getHolder().addCallback(cpHolderCallback);

        btn_take.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                camera.takePicture(null, null, new Camera.PictureCallback() {
                    @Override
                    public void onPictureTaken(byte[] data, Camera camera) {
                        String path
```java
// Initialize the camera
camera = Camera.open();
try {
    camera.setPreviewDisplay(sfv_preview.getHolder());
    camera.setDisplayOrientation(90);   // Rotate the camera by 90 degrees
    camera.startPreview();
} catch (IOException e) {
    e.printStackTrace();
}

// Stop the preview
private void stopPreview() {
    camera.stopPreview();
    camera.release();
    camera = null;
}

}
/**
 * Created by Jay on 2015/11/22 0022.
 */
public class PreviewActivity extends AppCompatActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ImageView img = new ImageView(this);
        String path = getIntent().getStringExtra("path");
        if(path != null){
            img.setImageURI(Uri.fromFile(new File(path)));
        }
        setContentView(img);
    }
}

Well, they are all very simple. Don't forget to add permissions:

&lt;uses-permission android:name="android.permission.CAMERA"/>
&lt;uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

Also, it's worth mentioning that if the camera is not released, the next call to the camera will result in an error. The error message is: java.lang.RuntimeException: fail to connect to camera service. So, it is necessary to release the camera with release(). If you keep getting the above error, please restart the phone.


3. Download the sample code for this section

CameraDemo1.zip

CameraDemo2.zip


Summary of this section

>

Okay, in this section, we explained how to use the built-in system camera to obtain the photo after taking a picture, as well as writing our own Camera to complete a custom camera. Hehe, in some situations, we don't need a camera preview interface. We can just make a floating window, and then click on the floating window to trigger the photo event. This can achieve stealthy shooting, right? (Sneak a photo)

-1.0 Android Basic Tutorial

-1.0.1 Latest Android Basic Tutorial Catalog for 2015

-1.1 Background and System Architecture Analysis

-1.2 Development Environment Setup

-1.2.1 Developing Android APPs with Eclipse + ADT + SDK

-1.2.2 Developing Android APPs with Android Studio

-1.3 Solving SDK Update Issues

-1.4 Genymotion Emulator Installation

-1.5.1 Git Tutorial on Basic Operations of Local Repositories

-1.5.2 Git: Using GitHub to Set Up a Remote Repository

-1.6 How to Play with 9 (Jiu Mei) Images

-1.7 Interface Prototype Design

-1.8 Project Related Analysis (Various Files, Resource Access)

-1.9 Android Program Signing and Packaging

-1.11 Decompiling APK to Obtain Code & Resources

-2.1 The Concept of View and ViewGroup

-2.2.1 LinearLayout (Linear Layout)

-2.2.2 RelativeLayout (Relative Layout)

-2.2.3 TableLayout (Table Layout)

-2.2.4 FrameLayout (Frame Layout)

-2.2.5 GridLayout (Grid Layout)

-2.2.6 AbsoluteLayout (Absolute Layout)

-2.3.1 TextView (Text Box) Detailed Explanation

-2.3.2 EditText (Input Box) Detailed Explanation

-2.3.3 Button (Button) and ImageButton (Image Button)

-[2.3.4 ImageView (Image View)](android

WeChat Follow

❮ Java Transient Keywords Linux Check Port Usage ❯