Android實現(xiàn)調(diào)用攝像頭和相冊的方法
Android調(diào)用攝像頭是很方便的。先看一下界面

布局文件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卡寫入數(shù)據(jù),所有需要在AndroidMainfest.xml中聲明響應(yīng)權(quán)限
<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) {
// 創(chuàng)建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())) {
// 解析出數(shù)字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);
}
// 根據(jù)圖片路徑顯示圖片
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();
}
}
}
調(diào)用攝像頭拍照
在MainActivity 中要做的第一件事自然是分別獲取到 Button 和 ImageView 的實例,并給 Button 注冊上點擊事件,然后在 Button的點擊事件里開始處理調(diào)用攝像頭的邏輯,我們重點看下這部分代碼。
首先這里創(chuàng)建了一個 File 對象,用于存儲攝像頭拍下的圖片,這里我們把圖片命名為saveImage.jpg ,并將它存放在手機SD卡的根目錄下,調(diào) 用 Environment 的getExternalStorageDirectory()方法獲取到的就是手機 SD 卡的根目錄。然后再調(diào)用 Uri 的fromFile()方法將 File 對象轉(zhuǎn)換成 Uri 對象,這個 Uri 對象標識著 saveImage.jpg 這張圖片的唯一地址。 接著構(gòu)建出一個 Intent對象, 并將這個 Intent的 action指定為android.media.action.IMAGE_CAPTURE,再調(diào)用 Intent 的 putExtra()方法指定圖片的輸出地址,這里填入剛剛得到的 Uri 對象,最后調(diào)用 startActivityForResult()來啟動活動。由于我們使用的是一個隱式Intent,系統(tǒng)會找出能夠響應(yīng)這個 Intent 的活動去啟動,這樣照相機程序就會被打開,拍下的照片將會輸出到 saveImage.jpg 中。
注意剛才我們是使用 startActivityForResult()來啟動活動的,因此拍完照后會有結(jié)果返回到 onActivityResult()方法中。如果發(fā)現(xiàn)拍照成功,則會再次構(gòu)建出一個 Intent 對象,并把它的 action 指定為 com.android.camera.action.CROP。這個 Intent 是用于對拍出的照片進行裁剪注意剛才我們是使用 startActivityForResult()來啟動活動的,因此拍完照后會有結(jié)果返回到 onActivityResult()方法中。如果發(fā)現(xiàn)拍照成功,則會再次構(gòu)建出一個 Intent 對象,并把它的 action 指定為 com.android.camera.action.CROP。這個 Intent 是用于對拍出的照片進行裁剪
從相冊中選擇照片
在 "從相冊中選擇圖片"按鈕的點擊事件里我們同樣創(chuàng)建了一個 File 對象,用于存儲從相冊中選擇的圖片。然后構(gòu)建出一個 Intent 對象,并將它的 action 指定為android.intent.action.GET_CONTENT。接著給這個 Intent 對象設(shè)置一些必要的參數(shù),包括是否允許縮放和裁剪、圖片的輸出位置等。最后調(diào)用 startActivityForResult()方法,就可以打開相冊程序選擇照片了。
注意在調(diào)用 startActivityForResult()方法的時候,我們給第二個參數(shù)傳入的值仍然是CROP_PHOTO 常量,這樣的好處就是從相冊選擇好照片之后,會直接進入到 CROP_PHOTO的 case 下將圖片顯示出來, 這樣就可以復(fù)用之前寫好的顯示圖片的邏輯, 不用再編寫一遍了。
參考資料
1、《第一行代碼-Android》調(diào)用攝像頭章節(jié)
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- Android實現(xiàn)手機攝像頭的自動對焦
- android開發(fā)之調(diào)用手機的攝像頭使用MediaRecorder錄像并播放
- Android開發(fā)教程之調(diào)用攝像頭功能的方法詳解
- Android實現(xiàn)調(diào)用攝像頭進行拍照功能
- Android實現(xiàn)調(diào)用攝像頭拍照與視頻功能
- Android調(diào)用前后攝像頭同時工作實例代碼
- Android實現(xiàn)調(diào)用攝像頭
- Android調(diào)用系統(tǒng)攝像頭拍照并顯示在ImageView上
- Android讀取本地圖庫與調(diào)用攝像頭拍攝
- Android調(diào)用手機攝像頭的方法
相關(guān)文章
自定義View系列之kotlin繪制手勢設(shè)置溫度控件的方法
這篇文章主要給大家介紹了關(guān)于自定義View系列之kotlin繪制手勢設(shè)置溫度控件的相關(guān)資料,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2018-07-07
Android LocationManager獲取經(jīng)度與緯度等地理信息
這篇文章主要介紹了Android LocationManager獲取經(jīng)度與緯度等地理信息的相關(guān)資料,希望通過本站大家能掌握這樣的知識,需要的朋友可以參考下2017-09-09
Android使用Messenger實現(xiàn)service與activity交互
這篇文章主要介紹了android使用Messenger實現(xiàn)service與activity交互的相關(guān)資料,需要的朋友可以參考下2016-06-06
android導(dǎo)入第三方j(luò)ar包報錯 如何正確導(dǎo)入jar包
怎樣在android平臺上使用第三方j(luò)ar包,為什么我在引入了,編譯時沒有錯誤,運行時就有錯誤,報無法實例化錯誤,請問這是什么原因,本文給于解決方法,需要了解的朋友可以參考下2012-12-12
Android 開發(fā)之dataBinding與ListView及事件
這篇文章主要介紹了Android 開發(fā)之dataBinding與ListView及事件的相關(guān)資料,非常不錯,具有參考借鑒價值,需要的朋友可以參考下2016-10-10

