Android Camera API 使用指南

查志強發表於2014-07-10

【原文:http://www.open-open.com/lib/view/open1327491133296.html

本教程介紹如何使用Android API中的攝像頭。本教程是基於Eclipse的3.7,JAVA1.6和Android4.0。

1. Android Camera

Most Android devices have a camera. Some devices have a front and a back camera.

Using the camera on the Android device can be done via integration of the existing Camera application. In this case you would start the existing Camera application via an Intent and to get the data after the user returns to our application.

You can also directly integrate the camera into your application via the Camera API.

01 package de.vogella.android.imagepick;
02  
03 import java.io.FileNotFoundException;
04 import java.io.IOException;
05 import java.io.InputStream;
06  
07 import android.app.Activity;
08 import android.content.Intent;
09 import android.graphics.Bitmap;
10 import android.graphics.BitmapFactory;
11 import android.os.Bundle;
12 import android.view.View;
13 import android.widget.ImageView;
14  
15 public class ImagePickActivity extends Activity {
16     private static final int REQUEST_CODE = 1;
17     private Bitmap bitmap;
18     private ImageView imageView;
19  
20      
21 /** Called when the activity is first created. */
22  
23     @Override
24     public void onCreate(Bundle savedInstanceState) {
25         super.onCreate(savedInstanceState);
26         setContentView(R.layout.main);
27         imageView = (ImageView) findViewById(R.id.result);
28     }
29  
30     public void pickImage(View View) {
31         Intent intent = new Intent();
32         intent.setType("image/*");
33         intent.setAction(Intent.ACTION_GET_CONTENT);
34         intent.addCategory(Intent.CATEGORY_OPENABLE);
35         startActivityForResult(intent, REQUEST_CODE);
36     }
37  
38     @Override
39     protected void onActivityResult(int requestCode, int resultCode, Intent data) {
40         if (requestCode == REQUEST_CODE && resultCode == Activity.RESULT_OK)
41             try {
42                 // We need to recyle unused bitmaps
43                 if (bitmap != null) {
44                     bitmap.recycle();
45                 }
46                 InputStream stream = getContentResolver().openInputStream(
47                         data.getData());
48                 bitmap = BitmapFactory.decodeStream(stream);
49                 stream.close();
50                 imageView.setImageBitmap(bitmap);
51             catch (FileNotFoundException e) {
52                 e.printStackTrace();
53             catch (IOException e) {
54                 e.printStackTrace();
55             }
56         super.onActivityResult(requestCode, resultCode, data);
57     }
58 }

3. Tutorial: Using the camera API

In this example we will an application which allow to make a photo via the front camera and to save it on the SD card. If you using the Android emulator make sure you added space for the SD card during the creation of the your Android virtual device.

Create a new Android project de.vogella.camera.api with an Activity called MakePhotoActivity .

Add the android.permission.CAMERA permission to access your camera and theandroid.permission.WRITE_EXTERNAL_STORAGE to be able to write to the SD card to your AndroidManifest.xml file.

01 <?xml version="1.0" encoding="utf-8"?>
02 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
03     package="de.vogella.cameara.api"
04     android:versionCode="1"
05     android:versionName="1.0" >
06  
07     <uses-sdk android:minSdkVersion="15" />
08     <uses-permission android:name="android.permission.CAMERA"/>
09     <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
10  
11     <application
12         android:icon="@drawable/ic_launcher"
13         android:label="@string/app_name" >
14         <activity
15             android:name="de.vogella.camera.api.MakePhotoActivity"
16             android:label="@string/app_name" >
17             <intent-filter>
18                 <action android:name="android.intent.action.MAIN" />
19  
20                 <category android:name="android.intent.category.LAUNCHER" />
21             </intent-filter>
22         </activity>
23     </application>
24  
25 </manifest>
26         
Change the "main.xml" file in the "res/layout" folder to the following
01 <?xml version="1.0" encoding="utf-8"?>
02 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
03     android:layout_width="match_parent"
04     android:layout_height="match_parent" >
05  
06     <Button
07         android:id="@+id/captureFront"
08         android:layout_width="wrap_content"
09         android:layout_height="wrap_content"
10         android:layout_centerInParent="true"
11         android:onClick="onClick"
12         android:text="Make Photo" />
13  
14 </RelativeLayout>
Create the following PhotoHandler class which will be responsible for saving the photo the the SD card.
01 package de.vogella.camera.api;
02  
03 import java.io.File;
04 import java.io.FileOutputStream;
05 import java.text.SimpleDateFormat;
06 import java.util.Date;
07  
08 import android.content.Context;
09 import android.hardware.Camera;
10 import android.hardware.Camera.PictureCallback;
11 import android.os.Environment;
12 import android.util.Log;
13 import android.widget.Toast;
14  
15 public class PhotoHandler implements PictureCallback {
16  
17     private final Context context;
18  
19     public PhotoHandler(Context context) {
20         this.context = context;
21     }
22  
23     @Override
24     public void onPictureTaken(byte[] data, Camera camera) {
25  
26         File pictureFileDir = getDir();
27  
28         if (!pictureFileDir.exists() && !pictureFileDir.mkdirs()) {
29  
30             Log.d(Constants.DEBUG_TAG, "Can't create directory to save image.");
31             Toast.makeText(context, "Can't create directory to save image.",
32                     Toast.LENGTH_LONG).show();
33             return;
34  
35         }
36  
37         SimpleDateFormat dateFormat = new SimpleDateFormat("yyyymmddhhmmss");
38         String date = dateFormat.format(new Date());
39         String photoFile = "Picture_" + date + ".jpg";
40  
41         String filename = pictureFileDir.getPath() + File.separator + photoFile;
42  
43         File pictureFile = new File(filename);
44  
45         try {
46             FileOutputStream fos = new FileOutputStream(pictureFile);
47             fos.write(data);
48             fos.close();
49             Toast.makeText(context, "New Image saved:" + photoFile,
50                     Toast.LENGTH_LONG).show();
51         catch (Exception error) {
52             Log.d(Constants.DEBUG_TAG, "File" + filename + "not saved: "
53                     + error.getMessage());
54             Toast.makeText(context, "Image could not be saved.",
55                     Toast.LENGTH_LONG).show();
56         }
57     }
58  
59     private File getDir() {
60         File sdDir = Environment
61           .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
62         return new File(sdDir, "CameraAPIDemo");
63     }
64 }
Change the MakePhotoActivity class to the following.
01 package de.vogella.camera.api;
02  
03 import android.app.Activity;
04 import android.content.pm.PackageManager;
05 import android.hardware.Camera;
06 import android.hardware.Camera.CameraInfo;
07 import android.os.Bundle;
08 import android.util.Log;
09 import android.view.View;
10 import android.widget.Toast;
11 import de.vogella.cameara.api.R;
12  
13 public class MakePhotoActivity extends Activity {
14     private final static String DEBUG_TAG = "MakePhotoActivity";
15     private Camera camera;
16     private int cameraId = 0;
17  
18     @Override
19     public void onCreate(Bundle savedInstanceState) {
20         super.onCreate(savedInstanceState);
21         setContentView(R.layout.main);
22  
23         // do we have a camera?
24         if (!getPackageManager()
25                 .hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
26             Toast.makeText(this"No camera on this device", Toast.LENGTH_LONG)
27                     .show();
28         else {
29             cameraId = findFrontFacingCamera();
30             camera = Camera.open(cameraId);
31             if (cameraId < 0) {
32                 Toast.makeText(this"No front facing camera found.",
33                         Toast.LENGTH_LONG).show();
34             }
35         }
36     }
37  
38     public void onClick(View view) {
39         camera.takePicture(nullnull,
40                 new PhotoHandler(getApplicationContext()));
41     }
42  
43     private int findFrontFacingCamera() {
44         int cameraId = -1;
45         // Search for the front facing camera
46         int numberOfCameras = Camera.getNumberOfCameras();
47         for (int i = 0; i < numberOfCameras; i++) {
48             CameraInfo info = new CameraInfo();
49             Camera.getCameraInfo(i, info);
50             if (info.facing == CameraInfo.CAMERA_FACING_FRONT) {
51                 Log.d(DEBUG_TAG, "Camera found");
52                 cameraId = i;
53                 break;
54             }
55         }
56         return cameraId;
57     }
58  
59     @Override
60     protected void onPause() {
61         if (camera != null) {
62             camera.release();
63             camera = null;
64         }
65         super.onPause();
66     }
67  
68 }

5. Questions and Discussion

Before posting questions, please see the vogella FAQ. If you have questions or find an error in this article please use the www.vogella.de Google Group. I have created a short list how to create good questions which might also help you.

6. Links and Literature

6.1. Source Code

Source Code of Examples

6.3. vogella Resources

Eclipse RCP Training (German) Eclipse RCP Training with Lars Vogel

Android Tutorial Introduction to Android Programming

GWT Tutorial Program in Java and compile to JavaScript and HTML

Eclipse RCP Tutorial Create native applications in Java

JUnit Tutorial Test your application

Git Tutorial Put everything you have under distributed version control system


相關文章