Call the camera to take a picture

Call the camera to take a picture:

@Override
public void onClick(View v) {
    //创建File对象,用于存储拍照后的图片
    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){
        //将File对象转化为封装过的Uri对象
        imageUri = FileProvider.getUriForFile(MainActivity.this,"com.eventstest.fileprovider",outputImage);
    }else {
        //将File对象转化为Uri对象
        imageUri = Uri.fromFile(outputImage);
    }
    //启动相机程序
    Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
     //将Intent的action指定,并且putExtra()指定图片的输出地址。(隐式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 {
                    //将拍摄的图片显示出来
                    //将output_image.jpg图片解析成bitmap对象。然后设置
                    Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri));
                    picture.setImageBitmap(bitmap);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
            }
            break;
        default:
            break;
    }
}
  • Reading and writing SD cards requires runtime permission processing, but using the associated directory can skip this step
  • If it is lower than Android 7.0, call Uri's fromFile() to convert the File object into a Uri object. Otherwise, call the getUriForFile() method of FileProvider to convert the File object into an encapsulated Uri object.
  • getUriForFile() accepts three parameters 1.Context 2. Can be any unique string 3. The File object just created. Since 7.0 it is considered unsafe to use the local real Uri directly. A FileExposedException will be thrown. The FileProvider is a special content provider that protects data and can selectively share the encapsulated Uri to the outside, thereby improving security.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324845953&siteId=291194637