Android實現(xiàn)調(diào)用攝像頭,選擇本地照片的功能

首先我們看布局代碼的文件:

<?xml version="1.0" encoding="utf-8"?>

? ? android:orientation="vertical"

? ? android:layout_width="match_parent"

? ? android:layout_height="match_parent"

? ? >

? ? ? ? android:id="@+id/bu_1"

? ? ? ? android:layout_width="match_parent"

? ? ? ? android:layout_height="wrap_content"

? ? ? ? android:text="Take Photo"/>

? ? ? ? android:id="@+id/choose_from_album"

? ? ? ? android:layout_width="match_parent"

? ? ? ? android:layout_height="wrap_content"

? ? ? ? android:text="chose from Album"/>

? ? ? ? android:id="@+id/picture"

? ? ? ? android:layout_width="wrap_content"

? ? ? ? android:layout_height="wrap_content"

? ? ? ? android:layout_gravity="center_horizontal"/>

圖中有兩個按鈕,一個是用來啟動照相機的,另一個是用來選擇本地照片的,還有一個ImageView控件,是用來顯示照片的

然后就是主函數(shù)中的代碼:

package com.example.pc_ly.cameraalbumtest;

import android.Manifest;

import android.annotation.TargetApi;

import android.content.ContentUris;

import android.content.Intent;

import android.content.pm.PackageManager;

import android.database.Cursor;

import android.graphics.Bitmap;

import android.graphics.BitmapFactory;

import android.net.Uri;

import android.os.Build;

import android.provider.DocumentsContract;

import android.provider.MediaStore;

import android.support.v4.app.ActivityCompat;

import android.support.v4.content.ContextCompat;

import android.support.v4.content.FileProvider;

import android.support.v7.app.AppCompatActivity;

import android.os.Bundle;

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;

import java.util.concurrent.Callable;

import static android.R.attr.handle;

public class MainActivityextends AppCompatActivity {

public static final int TAKE_PHOTO=1;

public static final int CHOOSE_PHOTO=2;

private ImageViewpicture;

private UriimageUri;

@Override

? ? protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

Button button=(Button)findViewById(R.id.bu_1);

picture=(ImageView)findViewById(R.id.picture);

Button choose=(Button)findViewById(R.id.choose_from_album);

choose.setOnClickListener(new View.OnClickListener() {

@Override

? ? ? ? ? ? public void onClick(View view) {//確認(rèn)是否有權(quán)限開啟

?if(ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED){

ActivityCompat.requestPermissions(MainActivity.this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},1);

}

else{

openAlbum();

}

}

});

button.setOnClickListener(new View.OnClickListener() {

@Override

? ? ? ? ? ? public void onClick(View view) {

File outputImage=new File(getExternalCacheDir(),"output_image.jpg");//用于存放攝像頭拍攝的照片

? ? ? ? ? ? ? ? try{

if (outputImage.exists()){

outputImage.delete();

}

outputImage.createNewFile();

}catch (IOException e){

e.printStackTrace();

}

if (Build.VERSION.SDK_INT>=24){//根據(jù)android的版本對URI執(zhí)行操作

? ? ? ? ? ? ? ? ? ? imageUri= FileProvider.getUriForFile(MainActivity.this,"com.example.pc_ly.cameraalbumtest.fileprovider",outputImage);}

else{imageUri=Uri.fromFile(outputImage);

}

Intent intent=new Intent("android.media.action.IMAGE_CAPTURE");//系統(tǒng)會找到能夠找到能響應(yīng)這個intent程序去執(zhí)行

? ? ? ? ? ? ? ? intent.putExtra(MediaStore.EXTRA_OUTPUT,imageUri);

startActivityForResult(intent,TAKE_PHOTO);

}

});

}

@Override

? ? protected void onActivityResult(int requestCode,int resultCode,Intent data){//如果拍照成功保屯,則會將照片顯示在容器中

? ? ? ? switch (requestCode){

case TAKE_PHOTO:

if(resultCode==RESULT_OK){

try{

Bitmap bitmap= BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri));

picture.setImageBitmap(bitmap);

}catch (FileNotFoundException e){

e.printStackTrace();

}

}

break;

case CHOOSE_PHOTO:

if(resultCode==RESULT_OK){

//判斷手機版本號

? ? ? ? ? ? ? ? ? ? if(Build.VERSION.SDK_INT>=19){

handleImageOnKitKat(data);

}

else{

handleImageBeforeKitKat(data);

}

}

default:

break;

}

}

public void openAlbum(){

Intent intent=new Intent("android.intent.action.GET_CONTENT");

intent.setType("image/*");

startActivityForResult(intent,CHOOSE_PHOTO);//打開相冊

? ? }

public void onRequestPermissionResult(int requestCode,String[] permissions,int[] grantResults){//看是否權(quán)限已經(jīng)打開

? ? ? ? switch (requestCode){

case 1:

if(grantResults.length>0&&grantResults[0]==PackageManager.PERMISSION_GRANTED){

openAlbum();

}

else{

Toast.makeText(this,"You denied the permission",Toast.LENGTH_SHORT).show();

}

break;

default:

}

}

@TargetApi(19)

private void handleImageOnKitKat(Intent data){//根據(jù)版本對uri進行解析

? ? ? ? String imagePath=null;

Uri uri=data.getData();

if(DocumentsContract.isDocumentUri(this,uri)){

//如果是document類型的Uri,則通過document id處理

? ? ? ? ? ? String docId=DocumentsContract.getDocumentId(uri);

if("com.android.providers.media.documents".equals(uri.getAuthority())){

String id=docId.split(":")[1];//解析出數(shù)字格式的id

? ? ? ? ? ? ? ? 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".equalsIgnoreCase(uri.getScheme())){

imagePath=getImagePath(uri,null);

}

else if("file".equalsIgnoreCase(uri.getScheme())){

imagePath=uri.getPath();

}

}

}

private void handleImageBeforeKitKat(Intent data){//老版本的解析

? ? ? ? Uri uri=data.getData();

String imagePath=getImagePath(uri,null);

displayImage(imagePath);

}

private String getImagePath(Uri uri,String selection){//獲取路徑

? ? ? ? String path=null;

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,"faild to get image",Toast.LENGTH_SHORT).show();

}

}

}

最后還有一個要注意一個重要的東西,要申明一下權(quán)限,如下圖:


上面的注釋已經(jīng)寫得很清楚了啦,我就不一一解釋了者甲,下面來看效果圖:


運行之后是這個界面虹曙,然后我們點擊take photo按鈕,就可以打開照相機啦,如下圖:


然后我們點擊CHOSE FROM ALBUM按鈕,就可以選擇照片文件啦:


好啦,這次就到這里啦臊诊,有什么疑問的話歡迎和我留言呀

郵箱:2321591758@qq.com

其他博客的鏈接:

Github個人網(wǎng)站??知乎??簡書

歡迎各位訪問哦匕积,這次就到這里啦芋绸!

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市葵蒂,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌重虑,老刑警劉巖践付,帶你破解...
    沈念sama閱讀 217,084評論 6 503
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異缺厉,居然都是意外死亡永高,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,623評論 3 392
  • 文/潘曉璐 我一進店門提针,熙熙樓的掌柜王于貴愁眉苦臉地迎上來命爬,“玉大人,你說我怎么就攤上這事辐脖∷峭穑” “怎么了?”我有些...
    開封第一講書人閱讀 163,450評論 0 353
  • 文/不壞的土叔 我叫張陵嗜价,是天一觀的道長艇抠。 經(jīng)常有香客問我,道長久锥,這世上最難降的妖魔是什么家淤? 我笑而不...
    開封第一講書人閱讀 58,322評論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮瑟由,結(jié)果婚禮上絮重,老公的妹妹穿的比我還像新娘。我一直安慰自己错妖,他們只是感情好绿鸣,可當(dāng)我...
    茶點故事閱讀 67,370評論 6 390
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著暂氯,像睡著了一般。 火紅的嫁衣襯著肌膚如雪亮蛔。 梳的紋絲不亂的頭發(fā)上痴施,一...
    開封第一講書人閱讀 51,274評論 1 300
  • 那天,我揣著相機與錄音究流,去河邊找鬼辣吃。 笑死,一個胖子當(dāng)著我的面吹牛芬探,可吹牛的內(nèi)容都是我干的神得。 我是一名探鬼主播,決...
    沈念sama閱讀 40,126評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼偷仿,長吁一口氣:“原來是場噩夢啊……” “哼哩簿!你這毒婦竟也來了宵蕉?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 38,980評論 0 275
  • 序言:老撾萬榮一對情侶失蹤节榜,失蹤者是張志新(化名)和其女友劉穎羡玛,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體宗苍,經(jīng)...
    沈念sama閱讀 45,414評論 1 313
  • 正文 獨居荒郊野嶺守林人離奇死亡稼稿,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,599評論 3 334
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了讳窟。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片让歼。...
    茶點故事閱讀 39,773評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖丽啡,靈堂內(nèi)的尸體忽然破棺而出是越,到底是詐尸還是另有隱情,我是刑警寧澤碌上,帶...
    沈念sama閱讀 35,470評論 5 344
  • 正文 年R本政府宣布倚评,位于F島的核電站,受9級特大地震影響馏予,放射性物質(zhì)發(fā)生泄漏天梧。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,080評論 3 327
  • 文/蒙蒙 一霞丧、第九天 我趴在偏房一處隱蔽的房頂上張望呢岗。 院中可真熱鬧,春花似錦蛹尝、人聲如沸后豫。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,713評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽挫酿。三九已至,卻和暖如春愕难,著一層夾襖步出監(jiān)牢的瞬間早龟,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,852評論 1 269
  • 我被黑心中介騙來泰國打工猫缭, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留葱弟,地道東北人。 一個月前我還...
    沈念sama閱讀 47,865評論 2 370
  • 正文 我出身青樓猜丹,卻偏偏與公主長得像芝加,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子射窒,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,689評論 2 354

推薦閱讀更多精彩內(nèi)容