Android实现调用摄像头,选择本地照片的功能

首先我们看布局代码的文件:

    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控件,是用来显示照片的

然后就是主函数中的代码:

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) {//确认是否有权限开启

 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){//根据android的版本对URI执行操作

                    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");//系统会找到能够找到能响应这个intent程序去执行

                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){//看是否权限已经打开

        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){//根据版本对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];//解析出数字格式的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();

}

}

}

最后还有一个要注意一个重要的东西,要申明一下权限,如下图:


上面的注释已经写得很清楚了啦,我就不一一解释了,下面来看效果图:


运行之后是这个界面,然后我们点击take photo按钮,就可以打开照相机啦,如下图:


然后我们点击CHOSE FROM ALBUM按钮,就可以选择照片文件啦:


好啦,这次就到这里啦,有什么疑问的话欢迎和我留言呀

邮箱:[email protected]

其他博客的链接:

Github个人网站  知乎  

欢迎各位访问哦,这次就到这里啦!

你可能感兴趣的:(Android实现调用摄像头,选择本地照片的功能)