Android-拍照上传图片

Android手机拍照获取图片资源的处理,Android 7之后发生了一些变化,以下是个人将拍照上传流程进行整理

第一步:配置mainfest, 添加provider(在application标签内)

//表示授予URI临时访问权限
    

第二步:在资源文件中配置上述provider中引用的provider_paths.xml文件,文件内容如下



    
    //path: 需要临时访问的路径(.代表所有路径)  name:给访问路径命名
    

第三步:Activity中的调用系统相机拍照业务流程

(1)判断是否有权限,如果没有权限则获取权限,如果有权限则调用相机

private void requestCameraPermission() {

    int camera = ContextCompat.checkSelfPermission(mContext, Manifest.permission.CAMERA);
    if (camera != PackageManager.PERMISSION_GRANTED) {
        mContext.requestPermissions(new String[]{Manifest.permission.CAMERA}, CAMERA_COD);
    } else {
        goTakePhoto();
    }
}

 

(2)启动相机拍照

/**
 * 去拍照
 */
private void goTakePhoto() {
    //注意:此处Intent不需要设置Data和Type
    Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    File file = new File(Environment.getExternalStorageDirectory(), System.currentTimeMillis() + ".jpg");

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {

        openCameraIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        tempUri = FileProvider.getUriForFile(BaseApplication.getInstance(), BuildConfig.APPLICATION_ID + ".fileProvider", file);
        saveUri = FileProvider.getUriForFile(BaseApplication.getInstance(), BuildConfig.APPLICATION_ID + ".fileProvider",
                new File(Environment.getExternalStorageDirectory(), "image.jpg"));
    } else {
        tempUri = Uri.fromFile(file);
        saveUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(), "image.jpg"));
    }
    openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, tempUri);
    mContext.startActivityForResult(openCameraIntent, TAKE_PICTURE);
}

 

(3)裁剪图片

/**
 * 裁剪图片方法实现
 *
 * @param uri
 */
protected void startPhotoZoom(Uri uri) {

    Intent intent = new Intent("com.android.camera.action.CROP");
    intent.setDataAndType(uri, "image/*");//此处的uri即第(2)中的tempUri
    intent.putExtra("crop", "true");
    intent.putExtra("aspectX", 1);
    intent.putExtra("aspectY", 1);
    intent.putExtra("outputX", 120);
    intent.putExtra("outputY", 120);
    intent.putExtra("return-data", false);
    intent.putExtra(MediaStore.EXTRA_OUTPUT, saveUri);
    mContext.startActivityForResult(intent, CROP_SMALL_PICTURE);
}

 

你可能感兴趣的:(Android)