Android調(diào)用攝像頭是很方便的。先看一下界面
創(chuàng)新互聯(lián)建站是一家集網(wǎng)站建設(shè),貢井企業(yè)網(wǎng)站建設(shè),貢井品牌網(wǎng)站建設(shè),網(wǎng)站定制,貢井網(wǎng)站建設(shè)報價,網(wǎng)絡(luò)營銷,網(wǎng)絡(luò)優(yōu)化,貢井網(wǎng)站推廣為一體的創(chuàng)新建站企業(yè),幫助傳統(tǒng)企業(yè)提升企業(yè)形象加強(qiáng)企業(yè)競爭力??沙浞譂M足這一群體相比中小企業(yè)更為豐富、高端、多元的互聯(lián)網(wǎng)需求。同時我們時刻保持專業(yè)、時尚、前沿,時刻以成就客戶成長自我,堅持不斷學(xué)習(xí)、思考、沉淀、凈化自己,讓我們?yōu)楦嗟钠髽I(yè)打造出實(shí)用型網(wǎng)站。
布局文件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="啟動相機(jī)" /> <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); // 啟動相機(jī) 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來獲取真實(shí)圖片路徑 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 的實(shí)例,并給 Button 注冊上點(diǎn)擊事件,然后在 Button的點(diǎn)擊事件里開始處理調(diào)用攝像頭的邏輯,我們重點(diǎn)看下這部分代碼。
首先這里創(chuàng)建了一個 File 對象,用于存儲攝像頭拍下的圖片,這里我們把圖片命名為saveImage.jpg ,并將它存放在手機(jī)SD卡的根目錄下,調(diào) 用 Environment 的getExternalStorageDirectory()方法獲取到的就是手機(jī) SD 卡的根目錄。然后再調(diào)用 Uri 的fromFile()方法將 File 對象轉(zhuǎn)換成 Uri 對象,這個 Uri 對象標(biāo)識著 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 的活動去啟動,這樣照相機(jī)程序就會被打開,拍下的照片將會輸出到 saveImage.jpg 中。
注意剛才我們是使用 startActivityForResult()來啟動活動的,因此拍完照后會有結(jié)果返回到 onActivityResult()方法中。如果發(fā)現(xiàn)拍照成功,則會再次構(gòu)建出一個 Intent 對象,并把它的 action 指定為 com.android.camera.action.CROP。這個 Intent 是用于對拍出的照片進(jìn)行裁剪注意剛才我們是使用 startActivityForResult()來啟動活動的,因此拍完照后會有結(jié)果返回到 onActivityResult()方法中。如果發(fā)現(xiàn)拍照成功,則會再次構(gòu)建出一個 Intent 對象,并把它的 action 指定為 com.android.camera.action.CROP。這個 Intent 是用于對拍出的照片進(jìn)行裁剪
從相冊中選擇照片
在 "從相冊中選擇圖片"按鈕的點(diǎn)擊事件里我們同樣創(chuàng)建了一個 File 對象,用于存儲從相冊中選擇的圖片。然后構(gòu)建出一個 Intent 對象,并將它的 action 指定為android.intent.action.GET_CONTENT。接著給這個 Intent 對象設(shè)置一些必要的參數(shù),包括是否允許縮放和裁剪、圖片的輸出位置等。最后調(diào)用 startActivityForResult()方法,就可以打開相冊程序選擇照片了。
注意在調(diào)用 startActivityForResult()方法的時候,我們給第二個參數(shù)傳入的值仍然是CROP_PHOTO 常量,這樣的好處就是從相冊選擇好照片之后,會直接進(jìn)入到 CROP_PHOTO的 case 下將圖片顯示出來, 這樣就可以復(fù)用之前寫好的顯示圖片的邏輯, 不用再編寫一遍了。
參考資料
1、《第一行代碼-Android》調(diào)用攝像頭章節(jié)
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持創(chuàng)新互聯(lián)。
分享標(biāo)題:Android實(shí)現(xiàn)調(diào)用攝像頭和相冊的方法
文章URL:http://jinyejixie.com/article22/johscc.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站建設(shè)、微信公眾號、App設(shè)計、品牌網(wǎng)站設(shè)計、ChatGPT、網(wǎng)站營銷
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)