调用Android系统自带相机拍照,从相册中获取图片(兼容7.0系统)

一,前言:

在日常的手机应用开发过程中,经常会遇到上传图片的需求,像上传头像之类的,这就需要调用系统的相机,相册获取照片。但是在Android 系统7.0之后认为这种操作是不安全的,这篇文章主要就是记录7.0获取照片遇到的问题。

 

二,FileProvider介绍

都说google官方文档是最好的学习资料,我也带着英语字典上来瞅了瞅。

https://developer.android.google.cn/reference/android/support/v4/content/FileProvider

1,借用google官方的原话:

FileProvider is a special subclass of ContentProvider that facilitates secure sharing of files associated with an app by creating a content:// Uri for a file instead of a file:/// Uri.

大致意思是说:FileProviders 是ContentProvider的子类,它通过创建content://Uri 来取代file:///Uri,从而有助于安全地共享与应用程序相关联的文件。。。。详细信息还是到google官网看吧

三,拍照

1,权限申请

  <uses-permission android:name="android.permission.CAMERA" />  
  <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

2,调用系统相机

    public void camera() {
        if (hasSdcard()) {
            Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
            tempFile = new File(Environment.getExternalStorageDirectory(),
                    PHOTO_FILE_NAME);
            Uri uri;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                uri = FileProvider.getUriForFile(
                        this, "com.camera.fileprovider",
                        tempFile);
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            } else {
                uri = Uri.fromFile(tempFile);
            }
            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
            startActivityForResult(intent, PHOTO_REQUEST_CAMERA);
        }
    }
 private boolean hasSdcard() {
        return Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED);
    }

1>调用相机之前我们可以创建一个临时文件tempFile指定拍照后原照片的位置

2>在7.0系统之后通过FileProvider.getUriForFile(Context context,String authority,File file);获取content://Uri代替file:///Uri。第二个参数authority和下文将要说到的android:authorities="com.camera.fileprovider" 一致

为Uri临时授权:

intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);

3>让系统将原照片存放在指定的位置

 intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);

3,在AndroidManifest.xml清单文件中注册FileProvider

  <provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="com.camera.fileProvider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/provider_paths"/>
   </provider>

1>name:使用v4中默认的FileProvider
2>authorities:和上一步中获取content://Uri保持一致。格式:xxx.fileprovider,xxx可以自定义
3>grantUriPermissions:是否允许为content://Uri赋予临时权限
4>meta-data:配置的是我们允许访问的文件的路径,需要使用XML文件进行配置。name是固定写法,resource是指定的配置的xml文件

4,在res目录下创建一个名为xml的文件夹,然后在该文件夹下创建名为provider_paths的xml文件

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
  
    <external-path
        name="external_storage_root"
        path="." />
    <external-path
        name="external_storage_root_file"
        path="./Demo/" />
</paths>

具体的路径和命名规则如下:

 

命名对应目录
<files-path name = "name" path = "path"/>Context.getFilesDir()
<cache-path name = "name" path = "path"/>Contest.getCacheDir()
<external-path name = "name" path = "path"/>Environment.getExternalStorageDirectory()
<external-files-path name = "name" path = "path"/>Context.getExternalFilesDir()
<external-cache-path name = "name" path = "path"/>Context.getExternalCacheDir()
<external-media-path name = "name" path = "path"/>Context.getExternalMediaDirs()

如果需要使用FileProvider获取某个目录下文件的uri,按照上表的对应关系在XML文件中声明就可以了

5,接收相机返回的code值

if (requestCode == PHOTO_REQUEST_CAMERA && resultCode == RESULT_OK) {
                Uri uri;
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    uri = FileProvider.getUriForFile(
                            this, "com.camera.fileprovider",
                            tempFile);
                } else{
                    uri = Uri.fromFile(tempFile);
}
 crop(uri);
}

1>根据临时文件拿到Uri

6,裁剪图片

 mCropImageFile = new File(Environment.getExternalStorageDirectory(),   //创建一个保存裁剪后照片的file
                 "crop_image.jpg");
        // 裁剪图片意图
        Intent intent = new Intent("com.android.camera.action.CROP");

        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        // 裁剪框的比例,1:1
        intent.putExtra("aspectX", 1);         //X方向上的比列
        intent.putExtra("aspectY", 1);         // Y方向上的比例
        intent.putExtra("outputX", 250);       //裁剪区的宽度
        intent.putExtra("outputY", 250);       //裁剪区的高度

        intent.putExtra("outputFormat", "JPEG");// 图片格式
        intent.putExtra("noFaceDetection", true);// 取消人脸识别
        intent.putExtra("return-data", false);  //是否在Intent中返回数据
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        }
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mCropImageFile));
        startActivityForResult(intent, PHOTO_REQUEST_CUT);

7,获取裁剪后的图片

if (requestCode == PHOTO_REQUEST_CUT) {
           Bitmap headerBitmap = BitmapFactory.decodeFile(mCropImageFile.getAbsolutePath());
            File file;
            if (headerBitmap != null)
                try {
                    file = BitmapToFile.saveFile(headerBitmap,  "crop.png");
                } catch (IOException e) {
                    e.printStackTrace();
                }

            try {
                if (tempFile != null)
                    tempFile.delete();

                if (mCropImageFile != null) {
                    mCropImageFile.delete();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

四,相册获取照片

1,调用系统相册

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

2,接收系统相册返回的数据

if (requestCode == PHOTO_REQUEST_GALLERY) {
            // 从相册返回的数据
            if (data != null) {
                // 得到图片的全路径
                Uri uri = data.getData();
                crop(uri);
            }
        }

1>返回的数据是Intent对像,getData()返回的就是相册中照片存放的Uri

3,裁剪和上面的逻辑是一样的,都是根据传入的Uri

 

 

 

 

 

  • 2
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值