Android拍照选取图片

Android拍照选取图片

Android经常会需要拍照、裁剪及图库中选择图片,其实都是通过intent调用系统相机或者系统图册,然后在onActivityResult中捕捉返回即可。

  • 正常拍照选择图片的代码:
例:

        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

在onActivityResult中通过返回的intent.getExtras().get("data")便可以获取图片,但Android默认可用的应用内存大约为16M.所以Android为了不超出内存限制,在拍照返回时通过intent返回的bitmap会被压缩,这样导致一直都是获取的小图。所以在拍照时如果想返回大图需要通过Uri返回。

#####拍照选择大图代码(tampUri为路径,开发者文档提供的代码):

        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        // 指定调用相机拍照后照片的储存路径
        intent.putExtra(MediaStore.EXTRA_OUTPUT, tempUri);
在onActivityResult中通过tempUri进行下一步操作。

说明:

存储图片的路径建议使用 Activity.this.getExternalCacheDir()返回的/storage/sdcard0/Android/data/<package name>/cache路径.
通过路径获取 Uri 的方法,需要对不同版本兼容处理:

7.0 以下系统: 使用 Uri.fromFile(new File(path)) 等即可.

String fileName = "temp.jpg";
File tmpFile = new File(this.getExternalCacheDir(),fileName);
Uri tmpUri = Uri.fromFile(tmpFile);
  • 7.0 系统上,因为不允许传递通过 intent 传递 file:// 路径, 如果设置 targetSDK 为 24(7.0), 系统相机则无法获得 Uri.需要使用以下方法来获取 Uri.
    注意:AndroidManifest 中的 provider authorities 与 FileProvider.getUriForFile(); 方法中 authority 一致

如:

    String authority = "com.text.images";

    FileProvider.getUriForFile(mContext, authority, filePath);

    <!-- grantUriPermissions:true,表示授予 URI 临时访问权限。 //exported:要求必须为false,为true则会报安全异常。 -->
            <provider
                android:name="android.support.v4.content.FileProvider"
                android:authorities="com.text.images"
                android:exported="false"
                android:grantUriPermissions="true">
                <meta-data
                    android:name="android.support.FILE_PROVIDER_PATHS"
                    android:resource="@xml/provider_paths" />
            </provider>


在 AndroidManifest.xml 中设置 provider:

 <provider
     android:authorities="${applicationId}"
     android:name="android.support.v4.content.FileProvider"
     android:exported="false"
     android:grantUriPermissions="true">
     <meta-data
         android:name="android.support.FILE_PROVIDER_PATHS"
          android:resource="@xml/provider_paths"/>
</provider>
在 res 目录下新建 xml 目录, 新建 provider_paths.xml 文件:

这里我使用了外部存储 external-path, 具体标签参考 FileProvider .

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

判断系统版本大于7.0时,采用 FileProvider 获取 Uri:

        tring fileName = "temp.jpg";
        File tmpFile = new File(this.getExternalCacheDir(),fileName);
        tmpUri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID, tmpFile)

为了防止Uri路径不对导致不能保存,使用前必须确保文件路径无误,不然会导致“无法保存剪裁的图片”的错误。或者无提示但不能点击确定保存图片。正确获取的Uri最终以file://开头

常见问题:

设置通过Uri返回后,onActivityResult中返回的intent为null。
开发者文档中只说了简单调用的方法,其实可以添加一些其他属性。

        intent.putExtra("return-data",false);
        intent.putExtra("outputFormat",Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true);
        不能添加intent.setType("image/*");,会因为找不到intent导致ActivityNotFoundException。
        intent.putExtra("android.intent.extras.CAMERA_FACING",1);,系统默认开启的是后置摄像头,如果希望选择前置摄像头可以加这句。

完整代码:

    Intent openPhotoIntent;
            if (Build.VERSION.SDK_INT < 19) {
                openPhotoIntent = new Intent();
                openPhotoIntent.setAction(Intent.ACTION_GET_CONTENT);
                openPhotoIntent.setType(mFileTypes);
            } else {
                openPhotoIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                openPhotoIntent.setType(mFileTypes);
            }
            return openPhotoIntent;



            Intent openPhotoIntent;
                    if (Build.VERSION.SDK_INT < 19) {
                        openPhotoIntent = new Intent();
                        openPhotoIntent.setAction(Intent.ACTION_GET_CONTENT);
                        openPhotoIntent.setType(mFileTypes);
                    } else {
                        openPhotoIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                        openPhotoIntent.setType(mFileTypes);
                    }
                    return openPhotoIntent;
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,663评论 25 708
  • ¥开启¥ 【iAPP实现进入界面执行逐一显】 〖2017-08-25 15:22:14〗 《//首先开一个线程,因...
    小菜c阅读 6,571评论 0 17
  • 临近期末,目前在进行Android课程设计,对于我这个压根不怎么学习的孩子来说,刚开始的完全是懵逼的,后来花两天时...
    站在冰箱上的姑娘阅读 24,207评论 5 41
  • 我们人生命只有一次呢,我要怎样才算不白来一趟,这个无法彩排的世界,每时每刻都得精打细算的珍惜!
    随缘而聚_466c阅读 104评论 0 0
  • 岁末新年,很多小伙伴都特别积极地晒出了2017年的计划,而我还迟迟没有动笔,不是想偷懒,而是希望自己真的想清楚,不...
    谈谈minda阅读 238评论 0 0