美文网首页
android 使用系统的拍照 选择图片 裁剪 中的坑

android 使用系统的拍照 选择图片 裁剪 中的坑

作者: numqin | 来源:发表于2018-06-22 10:56 被阅读17次

代码参考地址

  1. 调用拍照获取原图

    Intent captureCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    //加上下面这一句,拍照文件将保存到 file 中,android 7.0 使用 Uri.fromFile(file) 是不允许的需要额外处理,后面会讲
    captureCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
    startActivityForResult(captureCameraIntent, REQUEST_CAPTURE_CAMERA);
    
  2. 拍照时设置 putExtra(MediaStore.EXTRA_OUTPUT, imgUri); imgUri 的路径为 getCacheDir() 时无法保存,或无法获取到图片

    https://stackoverflow.com/questions/13407899/store-image-from-camera-into-private-app-cache-directory

    解决: getCacheDir() 改为其他路径 getExternalCacheDir() 可用

  3. android 7.0 兼容问题

    当需要共享一个文件给其他 app 使用时,android 7.0 以上需要通过 FileProvider 包装为 Uri ,而不是 Uri.fromFile(file)、

    1. 首先在清单文件中注册 FileProvider ,FileProvider 集成自 ContentProvider 所以需要清单中注册

    2. <provider
          android:name="android.support.v4.content.FileProvider"
          android:authorities="${applicationId}.fileProvider"
          android:exported="false"
          android:grantUriPermissions="true">
          <meta-data
              android:name="android.support.FILE_PROVIDER_PATHS"
              android:resource="@xml/file_paths" />
      </provider>
      
    3. android:resource="@xml/file_paths" 添加 file_paths.xml


      image.png

      file_paths 文件内容

      <?xml version="1.0" encoding="utf-8"?>
      <paths>
          <external-cache-path
              name="tokePhoto"
              path="." />
      </paths>
      
    4. 在需要使用的时候判断 android 版本大于等于 7.0 的使用 FileProvider

      if (Build.VERSION.SDK_INT >= 24) {
          Uri contentUri = FileProvider.getUriForFile(this,
                  BuildConfig.APPLICATION_ID + ".fileProvider", file);
          captureCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, contentUri);
      } else {
          captureCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
      } 
      

相关文章

网友评论

      本文标题:android 使用系统的拍照 选择图片 裁剪 中的坑

      本文链接:https://www.haomeiwen.com/subject/ikfkyftx.html