Android7.0实现拍照和相册选取图片功能

由于android 7.0新增了动态权限,所以我们在做拍照和相册选取功能的时候,需要申请添加动态权限

一、添加权限

1.在androidManifest.XML 文件申请相关权限

    
    
    

2.动态获取权限

 void takePhotoClick() {
  if (Build.VERSION.SDK_INT >= 23&&checkCallingOrSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
   requestPermissions(new String[]{Manifest.permission.CAMERA}, REQUEST_CODE_ASK_PERMISSIONS);
  } else {
   startActivityForResult(new Intent("android.media.action.IMAGE_CAPTURE"), TAKE_PICTURE);
  }
 }


 @Override
 public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
  switch (requestCode) {
   case REQUEST_CODE_ASK_PERMISSIONS:
    if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
     startActivityForResult(new Intent("android.media.action.IMAGE_CAPTURE"), TAKE_PICTURE);
    } else {
     // 没有打开相机的权限
     Toast.makeText(TakePhotoActivity.this, "没有打开照相机权限", Toast.LENGTH_SHORT).show();
    }
    break;
   default:
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
  }
 }

二、完整代码

1.JAVA代码



import android.Manifest;
import android.app.Activity;
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.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.format.DateFormat;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.example.examsystemapplication.R;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Calendar;
import java.util.Locale;

public class TakePhotoActivity extends Activity implements View.OnClickListener {
 private static final int REQUEST_CODE_ASK_PERMISSIONS = 0x01;
 private Button take_photo_btn;
 private Button select_photo_btn;
 private ImageView photo_iv;
 //使用照相机拍照获取图片
 public static final int TAKE_PHOTO_CODE = 1;
 //使用相册中的图片
 public static final int SELECT_PIC_CODE = 2;
 //图片裁剪
 private static final int PHOTO_CROP_CODE = 3;
 //定义图片的Uri
 private Uri photoUri;
 //图片文件路径
 private String picPath;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_take_pic);
  initViews();
 }

 private void initViews() {
  this.take_photo_btn = (Button) findViewById(R.id.take_photo_btn);
  this.take_photo_btn.setOnClickListener(this);
  this.select_photo_btn = (Button) findViewById(R.id.select_photo_btn);
  this.select_photo_btn.setOnClickListener(this);
  this.photo_iv = (ImageView) findViewById(R.id.photo_iv);
 }

 @Override
 public void onClick(View view) {
  switch (view.getId()) {
   //拍照
   case R.id.take_photo_btn:
     takePhotoClick();
    break;
   //选择图库
   case R.id.select_photo_btn:
    choose_photo_layout_click();
    break;
  }
 }

 private static final int TAKE_PICTURE = 0;

 void takePhotoClick() {
  if (Build.VERSION.SDK_INT >= 23&&checkCallingOrSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
   requestPermissions(new String[]{Manifest.permission.CAMERA}, REQUEST_CODE_ASK_PERMISSIONS);
  } else {
   startActivityForResult(new Intent("android.media.action.IMAGE_CAPTURE"), TAKE_PICTURE);
  }
 }

  @Override
  public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
   switch (requestCode) {
    case REQUEST_CODE_ASK_PERMISSIONS:
     if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
      startActivityForResult(new Intent("android.media.action.IMAGE_CAPTURE"), TAKE_PICTURE);
     } else {
      // 没有打开相机的权限
      Toast.makeText(TakePhotoActivity.this, "没有打开照相机权限", Toast.LENGTH_SHORT).show();
     }
     break;
    default:
     super.onRequestPermissionsResult(requestCode, permissions, grantResults);
   }
  }

 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  if (requestCode == TAKE_PICTURE && resultCode == RESULT_OK && null != data) {
   String sdState = Environment.getExternalStorageState();
   if (!sdState.equals(Environment.MEDIA_MOUNTED)) {
    return;
   }
   String name = DateFormat.format("yyyyMMdd_hhmmss", Calendar.getInstance(Locale.CHINA)) + ".jpg";
   Bundle bundle = data.getExtras();
   //获取相机返回的数据,并转换为图片格式
   Bitmap bitmap = (Bitmap) bundle.get("data");
   FileOutputStream fout = null;
   File file = new File("/sdcard/pics/");
   file.mkdirs();
   String filename = file.getPath() + name;
   try {
    fout = new FileOutputStream(filename);
    bitmap.compress(Bitmap.CompressFormat.JPEG, 80, fout);
    System.out.println("拍照图片地址:"+file.getPath());
    showImage(filename);
   } catch (FileNotFoundException e) {
    e.printStackTrace();
   } finally {
    try {
     fout.flush();
     fout.close();
    } catch (IOException e) {
     e.printStackTrace();
    }
   }
   //显示图片
  }

  //获取图片路径
  if (requestCode == IMAGE && resultCode == Activity.RESULT_OK && data != null) {
   Uri selectedImage = data.getData();
   String[] filePathColumns = {MediaStore.Images.Media.DATA};
   Cursor c = getContentResolver().query(selectedImage, filePathColumns, null, null, null);
   c.moveToFirst();
   int columnIndex = c.getColumnIndex(filePathColumns[0]);
   String imagePath = c.getString(columnIndex);
   showImage(imagePath);
   c.close();
  }
 }


 private static final int IMAGE = 1;
 void choose_photo_layout_click() {
  //调用相册
  Intent intent = new Intent(Intent.ACTION_PICK,
          android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
  startActivityForResult(intent, IMAGE);
 }


 //加载图片
 private void showImage(String imaePath){
  System.out.println("拍照图片地址:"+imaePath);
  Bitmap bm = BitmapFactory.decodeFile(imaePath);
  photo_iv.setImageBitmap(bm);
 }
}

2.XML布局




    

    

    

发现一个不错的开源框架EasyPhotos,兼容Android10,传送门https://github.com/HuanTanSheng/EasyPhotos

你可能感兴趣的:(Android7.0实现拍照和相册选取图片功能)