Android調用攝像頭是很方便的。先看一下界面
	
布局文件activity_main.xml源碼
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <Button android:id="@+id/take_photo" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="啟動相機" /> <Button android:id="@+id/choose_from_album" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="從相冊中選擇圖片" /> <ImageView android:id="@+id/picture" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" /> </LinearLayout>
因為涉及到向SD卡寫入數據,所有需要在AndroidMainfest.xml中聲明響應權限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
MainActivity.java源碼
package com.example.luoxn28.activity;  import android.annotation.TargetApi; import android.content.ContentUris; import android.content.Intent; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.provider.DocumentsContract; import android.provider.MediaStore; import android.support.v7.app.ActionBarActivity; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.Toast;  import java.io.File; import java.io.FileNotFoundException; import java.io.IOException;  public class MainActivity extends ActionBarActivity {   private static final String TAG = "hdu";    public static final int TAKE_PHOTO = 1;   public static final int CROP_PHOTO = 2;   public static final int CHOOSE_PHOTO = 3;    private Button takePhoto;   private ImageView picture;   private Uri imageUri;    private Button chooseFromAlbum;    @Override   protected void onCreate(Bundle savedInstanceState) {     super.onCreate(savedInstanceState);     //requestWindowFeature(Window.FEATURE_NO_TITLE);     setContentView(R.layout.activity_main);      takePhoto = (Button) findViewById(R.id.take_photo);     picture = (ImageView) findViewById(R.id.picture);     chooseFromAlbum = (Button) findViewById(R.id.choose_from_album);      takePhoto.setOnClickListener(new View.OnClickListener() {       @Override       public void onClick(View v) {         // 創建File對象,用于存儲拍攝后照片         File saveImage = new File(Environment.getExternalStorageDirectory(), "saveImage.jpg");         try {           if (saveImage.exists()) {             saveImage.delete();           }           saveImage.createNewFile();         }         catch (IOException ex) {           ex.printStackTrace();         }          imageUri = Uri.fromFile(saveImage);         Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");         intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);         // 啟動相機         startActivityForResult(intent, TAKE_PHOTO);       }     });      chooseFromAlbum.setOnClickListener(new View.OnClickListener() {       @Override       public void onClick(View v) {         Intent intent = new Intent("android.intent.action.GET_CONTENT");         intent.setType("image/*");         // 打開相冊         startActivityForResult(intent, CHOOSE_PHOTO);       }     });   }    @Override   protected void onActivityResult(int requestCode, int resultCode, Intent data) {     switch (requestCode) {       case TAKE_PHOTO:         if (resultCode == RESULT_OK) {           Intent intent = new Intent("com.android.camera.action.CROP");           intent.setDataAndType(imageUri, "image/*");           intent.putExtra("scale", true);           intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);           // 啟動裁剪程序           startActivityForResult(intent, CROP_PHOTO);         }         break;        case CROP_PHOTO:         if (resultCode == RESULT_OK) {           try {             Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri));             // 顯示裁剪后的圖片             picture.setImageBitmap(bitmap);           }           catch (FileNotFoundException ex) {             ex.printStackTrace();           }         }         break;        case CHOOSE_PHOTO:         if (resultCode == RESULT_OK) {           handleImage(data);         }         break;        default:         break;     }   }    // 只在Android4.4及以上版本使用   @TargetApi(19)   private void handleImage(Intent data) {     String imagePath = null;     Uri uri = data.getData();      if (DocumentsContract.isDocumentUri(this, uri)) {       // 通過document id來處理       String docId = DocumentsContract.getDocumentId(uri);       if ("com.android.providers.media.documents".equals(uri.getAuthority())) {         // 解析出數字id         String id = docId.split(":")[1];         String selection = MediaStore.Images.Media._ID + "=" + id;         imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);       }       else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())) {         Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"),             Long.valueOf(docId));         imagePath = getImagePath(contentUri, null);       }     }     else if ("content".equals(uri.getScheme())) {       // 如果不是document類型的Uri,則使用普通方式處理       imagePath = getImagePath(uri, null);     }      // 根據圖片路徑顯示圖片     displayImage(imagePath);   }    private String getImagePath(Uri uri, String selection) {     String path = null;     // 通過Uri和selection來獲取真實圖片路徑     Cursor cursor = getContentResolver().query(uri, null, selection, null, null);     if (cursor != null) {       if (cursor.moveToFirst()) {         path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));       }       cursor.close();     }      return path;   }    private void displayImage(String imagePath) {     if (imagePath != null) {       Bitmap bitmap = BitmapFactory.decodeFile(imagePath);       picture.setImageBitmap(bitmap);     }     else {       Toast.makeText(this, "failed to get image", Toast.LENGTH_SHORT).show();     }   } } 調用攝像頭拍照
	       在MainActivity 中要做的第一件事自然是分別獲取到 Button 和 ImageView 的實例,并給 Button 注冊上點擊事件,然后在 Button的點擊事件里開始處理調用攝像頭的邏輯,我們重點看下這部分代碼。
	       首先這里創建了一個 File 對象,用于存儲攝像頭拍下的圖片,這里我們把圖片命名為saveImage.jpg ,并將它存放在手機SD卡的根目錄下,調 用 Environment 的getExternalStorageDirectory()方法獲取到的就是手機 SD 卡的根目錄。然后再調用 Uri 的fromFile()方法將 File 對象轉換成 Uri 對象,這個 Uri 對象標識著 saveImage.jpg 這張圖片的唯一地址。 接著構建出一個 Intent對象, 并將這個 Intent的 action指定為android.media.action.IMAGE_CAPTURE,再調用 Intent 的 putExtra()方法指定圖片的輸出地址,這里填入剛剛得到的 Uri 對象,最后調用 startActivityForResult()來啟動活動。由于我們使用的是一個隱式Intent,系統會找出能夠響應這個 Intent 的活動去啟動,這樣照相機程序就會被打開,拍下的照片將會輸出到 saveImage.jpg 中。
注意剛才我們是使用 startActivityForResult()來啟動活動的,因此拍完照后會有結果返回到 onActivityResult()方法中。如果發現拍照成功,則會再次構建出一個 Intent 對象,并把它的 action 指定為 com.android.camera.action.CROP。這個 Intent 是用于對拍出的照片進行裁剪注意剛才我們是使用 startActivityForResult()來啟動活動的,因此拍完照后會有結果返回到 onActivityResult()方法中。如果發現拍照成功,則會再次構建出一個 Intent 對象,并把它的 action 指定為 com.android.camera.action.CROP。這個 Intent 是用于對拍出的照片進行裁剪
從相冊中選擇照片
在 "從相冊中選擇圖片"按鈕的點擊事件里我們同樣創建了一個 File 對象,用于存儲從相冊中選擇的圖片。然后構建出一個 Intent 對象,并將它的 action 指定為android.intent.action.GET_CONTENT。接著給這個 Intent 對象設置一些必要的參數,包括是否允許縮放和裁剪、圖片的輸出位置等。最后調用 startActivityForResult()方法,就可以打開相冊程序選擇照片了。
注意在調用 startActivityForResult()方法的時候,我們給第二個參數傳入的值仍然是CROP_PHOTO 常量,這樣的好處就是從相冊選擇好照片之后,會直接進入到 CROP_PHOTO的 case 下將圖片顯示出來, 這樣就可以復用之前寫好的顯示圖片的邏輯, 不用再編寫一遍了。
參考資料
1、《第一行代碼-Android》調用攝像頭章節
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VEVB武林網。
新聞熱點
疑難解答