头像的截取 包括相册和相机

话不多说 上代码
权限呢需要内存的读取权限

先写隐式启动相册相机,这里使用的是startActivityForResult

/*相册*/
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, 500);

/*相机*/
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(path)));
startActivityForResult(intent, 1000);

接下来就是一个Activity的回调

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == 500 && resultCode == RESULT_OK) {
            Uri uri = data.getData();
            Intent intent = new Intent("com.android.camera.action.CROP");

            intent.setDataAndType(uri, "image/*");

            intent.putExtra("crop", true);
            intent.putExtra("aspectX", 1);
            intent.putExtra("aspectY", 1);
            intent.putExtra("outputX", 250);
            intent.putExtra("outputY", 250);
            intent.putExtra("return-data", true);

            startActivityForResult(intent, 200);
        }
        if (requestCode == 1000 && resultCode == RESULT_OK) {

            Intent intent = new Intent("com.android.camera.action.CROP");

            intent.setDataAndType(Uri.fromFile(new File(path)), "image/*");

            intent.putExtra("crop", true);
            intent.putExtra("aspectX", 1);
            intent.putExtra("aspectY", 1);
            intent.putExtra("outputX", 250);
            intent.putExtra("outputY", 250);
            intent.putExtra("return-data", true);

            startActivityForResult(intent, 200);
        }

        if (requestCode == 200 && resultCode == RESULT_OK) {
            Bitmap bitmap = data.getParcelableExtra("data");
            img_tou.setImageBitmap(bitmap);
        }

    }

在Android7.0之后访问内存就不能直接访问了 除了6.0的权限申请之外还要使用FileProvider不然会报异常

//在SRC文件夹目录下添加 XML目录 并创建 file_paths
//用于访问图片路径
<resources xmlns:android="http://schemas.android.com/apk/res/android">
    <paths>
        <external-path
            name="image"
            path="" />
    </paths>
</resources>

//清单文件 Application内添加
<provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="com.onlyboss.android.fileProvider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_paths" />
        </provider>
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页