Android Camera API 使用指南

fmms 13年前
     本教程介绍如何使用Android API中的摄像头。本教程是基于Eclipse的3.7,JAVA1.6和Android4.0。    <div class="toc">     <p><b>目录</b></p>     <dl>      <dt>       <span class="section"><a href="http://www.open-open.com/lib/view/open1327491133296.html#overview">1. Android Camera</a></span>      </dt>      <dt>       <span class="section"><a href="http://www.open-open.com/lib/view/open1327491133296.html#example">2. Tutorial: Using an Intent to make a photo</a></span>      </dt>      <dt>       <span class="section"><a href="http://www.open-open.com/lib/view/open1327491133296.html#tutorial_cameraapi">3. Tutorial: Using the camera API</a></span>      </dt>      <dt>       <span class="section"><a href="http://www.open-open.com/lib/view/open1327491133296.html#thankyou">4. Thank you </a></span>      </dt>      <dt>       <span class="section"><a href="http://www.open-open.com/lib/view/open1327491133296.html#questions">5. Questions and Discussion</a></span>      </dt>      <dt>       <span class="section"><a href="http://www.open-open.com/lib/view/open1327491133296.html#resources">6. Links and Literature</a></span>      </dt>      <dd>       <dl>        <dt>         <span class="section"><a href="http://www.open-open.com/lib/view/open1327491133296.html#sourcecode">6.1. Source Code</a></span>        </dt>        <dt>         <span class="section"><a href="http://www.open-open.com/lib/view/open1327491133296.html#resources_databinding">6.2. Android Resources</a></span>        </dt>        <dt>         <span class="section"><a href="http://www.open-open.com/lib/view/open1327491133296.html#resources_general">6.3. vogella Resources</a></span>        </dt>       </dl>      </dd>     </dl>    </div>    <div class="section">     <div class="titlepage">      <div>       <div>        <h2 style="clear:both;" class="title"><a name="overview"></a>1. Android Camera</h2>       </div>      </div>     </div>     <p>Most Android devices have a camera. Some devices have a front and a back camera. </p>     <p>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 <code class="code">Intent</code> and to get the data after the user returns to our application. </p>     <p>You can also directly integrate the camera into your application via the <code class="code">Camera</code> API. </p>     <pre class="brush:java; toolbar: true; auto-links: false;">package de.vogella.android.imagepick;  import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream;  import android.app.Activity; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Bundle; import android.view.View; import android.widget.ImageView;  public class ImagePickActivity extends Activity {  private static final int REQUEST_CODE = 1;  private Bitmap bitmap;  private ImageView imageView;    /** Called when the activity is first created. */   @Override  public void onCreate(Bundle savedInstanceState) {   super.onCreate(savedInstanceState);   setContentView(R.layout.main);   imageView = (ImageView) findViewById(R.id.result);  }   public void pickImage(View View) {   Intent intent = new Intent();   intent.setType("image/*");   intent.setAction(Intent.ACTION_GET_CONTENT);   intent.addCategory(Intent.CATEGORY_OPENABLE);   startActivityForResult(intent, REQUEST_CODE);  }   @Override  protected void onActivityResult(int requestCode, int resultCode, Intent data) {   if (requestCode == REQUEST_CODE && resultCode == Activity.RESULT_OK)    try {     // We need to recyle unused bitmaps     if (bitmap != null) {      bitmap.recycle();     }     InputStream stream = getContentResolver().openInputStream(       data.getData());     bitmap = BitmapFactory.decodeStream(stream);     stream.close();     imageView.setImageBitmap(bitmap);    } catch (FileNotFoundException e) {     e.printStackTrace();    } catch (IOException e) {     e.printStackTrace();    }   super.onActivityResult(requestCode, resultCode, data);  } }</pre>     <p></p>     <h2 style="clear:both;" class="title">3. Tutorial: Using the camera API</h2>     <p>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. </p>     <p>Create a new Android project <code class="code">de.vogella.camera.api</code> with an <code class="code">Activity</code> called <code class="code">MakePhotoActivity </code>. </p>     <p>Add the <code class="code">android.permission.CAMERA</code> permission to access your camera and the <code class="code">android.permission.WRITE_EXTERNAL_STORAGE</code> to be able to write to the SD card to your AndroidManifest.xml file. </p>     <pre class="brush:xml; toolbar: true; auto-links: false;"><?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android"     package="de.vogella.cameara.api"     android:versionCode="1"     android:versionName="1.0" >      <uses-sdk android:minSdkVersion="15" />     <uses-permission android:name="android.permission.CAMERA"/>     <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>      <application         android:icon="@drawable/ic_launcher"         android:label="@string/app_name" >         <activity             android:name="de.vogella.camera.api.MakePhotoActivity"             android:label="@string/app_name" >             <intent-filter>                 <action android:name="android.intent.action.MAIN" />                  <category android:name="android.intent.category.LAUNCHER" />             </intent-filter>         </activity>     </application>  </manifest>   </pre>Change the "main.xml" file in the "res/layout" folder to the following     <pre class="brush:xml; toolbar: true; auto-links: false;"><?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" >      <Button         android:id="@+id/captureFront"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:layout_centerInParent="true"         android:onClick="onClick"         android:text="Make Photo" />  </RelativeLayout></pre>Create the following     <code class="code">PhotoHandler</code> class which will be responsible for saving the photo the the SD card.     <pre class="brush:java; toolbar: true; auto-links: false;">package de.vogella.camera.api;  import java.io.File; import java.io.FileOutputStream; import java.text.SimpleDateFormat; import java.util.Date;  import android.content.Context; import android.hardware.Camera; import android.hardware.Camera.PictureCallback; import android.os.Environment; import android.util.Log; import android.widget.Toast;  public class PhotoHandler implements PictureCallback {   private final Context context;   public PhotoHandler(Context context) {   this.context = context;  }   @Override  public void onPictureTaken(byte[] data, Camera camera) {    File pictureFileDir = getDir();    if (!pictureFileDir.exists() && !pictureFileDir.mkdirs()) {     Log.d(Constants.DEBUG_TAG, "Can't create directory to save image.");    Toast.makeText(context, "Can't create directory to save image.",      Toast.LENGTH_LONG).show();    return;    }    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyymmddhhmmss");   String date = dateFormat.format(new Date());   String photoFile = "Picture_" + date + ".jpg";    String filename = pictureFileDir.getPath() + File.separator + photoFile;    File pictureFile = new File(filename);    try {    FileOutputStream fos = new FileOutputStream(pictureFile);    fos.write(data);    fos.close();    Toast.makeText(context, "New Image saved:" + photoFile,      Toast.LENGTH_LONG).show();   } catch (Exception error) {    Log.d(Constants.DEBUG_TAG, "File" + filename + "not saved: "      + error.getMessage());    Toast.makeText(context, "Image could not be saved.",      Toast.LENGTH_LONG).show();   }  }   private File getDir() {   File sdDir = Environment     .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);   return new File(sdDir, "CameraAPIDemo");  } }</pre>Change the     <code class="code">MakePhotoActivity </code>class to the following.     <pre class="brush:java; toolbar: true; auto-links: false;">package de.vogella.camera.api;  import android.app.Activity; import android.content.pm.PackageManager; import android.hardware.Camera; import android.hardware.Camera.CameraInfo; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Toast; import de.vogella.cameara.api.R;  public class MakePhotoActivity extends Activity {  private final static String DEBUG_TAG = "MakePhotoActivity";  private Camera camera;  private int cameraId = 0;   @Override  public void onCreate(Bundle savedInstanceState) {   super.onCreate(savedInstanceState);   setContentView(R.layout.main);    // do we have a camera?   if (!getPackageManager()     .hasSystemFeature(PackageManager.FEATURE_CAMERA)) {    Toast.makeText(this, "No camera on this device", Toast.LENGTH_LONG)      .show();   } else {    cameraId = findFrontFacingCamera();    camera = Camera.open(cameraId);    if (cameraId < 0) {     Toast.makeText(this, "No front facing camera found.",       Toast.LENGTH_LONG).show();    }   }  }   public void onClick(View view) {   camera.takePicture(null, null,     new PhotoHandler(getApplicationContext()));  }   private int findFrontFacingCamera() {   int cameraId = -1;   // Search for the front facing camera   int numberOfCameras = Camera.getNumberOfCameras();   for (int i = 0; i < numberOfCameras; i++) {    CameraInfo info = new CameraInfo();    Camera.getCameraInfo(i, info);    if (info.facing == CameraInfo.CAMERA_FACING_FRONT) {     Log.d(DEBUG_TAG, "Camera found");     cameraId = i;     break;    }   }   return cameraId;  }   @Override  protected void onPause() {   if (camera != null) {    camera.release();    camera = null;   }   super.onPause();  }  }</pre>     <p></p>     <div class="section">      <div class="titlepage">       <div>        <div>         <h2 style="clear:both;" class="title">5. Questions and Discussion</h2>        </div>       </div>      </div>      <p>Before posting questions, please see the <a class="ulink" href="/misc/goto?guid=4959517512682003467" target="_top">vogella FAQ</a>. If you have questions or find an error in this article please use the <a class="ulink" href="/misc/goto?guid=4959517512787035789" target="_top">www.vogella.de Google Group</a>. I have created a short list <a class="ulink" href="/misc/goto?guid=4959517512892559718" target="_top">how to create good questions </a>which might also help you. </p>     </div>     <div class="section">      <div class="titlepage">       <div>        <div>         <h2 style="clear:both;" class="title"><a name="resources"></a>6. Links and Literature</h2>        </div>       </div>      </div>      <div class="section">       <div class="titlepage">        <div>         <div>          <h3 class="title"><a name="sourcecode"></a>6.1. Source Code</h3>         </div>        </div>       </div>       <p><a class="ulink" href="/misc/goto?guid=4959517513018208352" target="_top">Source Code of Examples</a> </p>      </div>      <div class="section">       <div class="titlepage">        <div>         <div>          <h3 class="title"><a name="resources_databinding"></a>6.2. Android Resources</h3>         </div>        </div>       </div>       <p><a class="ulink" href="/misc/goto?guid=4958191046825680296" target="_top">Android Tutorial </a></p>       <p><a class="ulink" href="/misc/goto?guid=4959517513148402413" target="_top">Android Location API and Google Maps </a></p>       <p><a class="ulink" href="/misc/goto?guid=4959517513252413716" target="_top">Android and Networking </a></p>      </div>      <div class="section">       <div class="titlepage">        <div>         <div>          <h3 class="title"><a name="resources_general"></a>6.3. vogella Resources</h3>         </div>        </div>       </div>       <p><a class="ulink" href="/misc/goto?guid=4959517513352111191" target="_top">Eclipse RCP Training </a>(German) Eclipse RCP Training with Lars Vogel </p>       <p><a class="ulink" href="/misc/goto?guid=4958191046825680296" target="_top">Android Tutorial </a>Introduction to Android Programming </p>       <p><a class="ulink" href="/misc/goto?guid=4959517513475716181" target="_top">GWT Tutorial </a>Program in Java and compile to JavaScript and HTML </p>       <p><a class="ulink" href="/misc/goto?guid=4959517513573818432" target="_top">Eclipse RCP Tutorial </a>Create native applications in Java </p>       <p><a class="ulink" href="/misc/goto?guid=4959517513681426878" target="_top">JUnit Tutorial </a>Test your application </p>       <p><a class="ulink" href="/misc/goto?guid=4959517513777201987" target="_top">Git Tutorial </a>Put everything you have under distributed version control system </p>      </div>     </div>    </div>