Zoh*_*Ali 3 android android-camera
对于版主:我知道已经存在这样的问题,但所有这些方法最终都会给出位图,data.getExtra("data")实际上只是thumbnail. 我想要获取 URI 而不是位图,并且我需要使用2021. 在将问题标记为重复之前,请考虑这一点!
我从相机获取图像,它在较低设备上工作正常,但onActivityResult仅在 Android 10 和 11 中调用时它在数据中给出空值。
这就是我正在做的
val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
startActivityForResult(intent, ACTION_REQUEST_CAMERA)
Run Code Online (Sandbox Code Playgroud)
这是我的 onActivityResult
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (resultCode == RESULT_OK && requestCode == ACTION_REQUEST_CAMERA) {
data?.data?.let { uri ->
Toast.makeText(context, "Got URI", Toast.LENGTH_LONG).show()
}
}
}
Run Code Online (Sandbox Code Playgroud)
这种方法对我有用
在Manifest文件中
<application>
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="com.example.android.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths">
</meta-data>
</provider>
...
</application
Run Code Online (Sandbox Code Playgroud)
创建了一个文件/res/xml/file_paths.xml并在其中指定了路径
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-files-path name="my_images" path="Pictures" />
</paths>
Run Code Online (Sandbox Code Playgroud)
在我的activity
创建了一个全局变量var cameraPhotoFilePath: Uri? = null
这就是我开始相机活动以获得结果的方式
val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
val photoFile: File? = try {
createImageFileInAppDir()
} catch (ex: IOException) {
// Error occurred while creating the File
null
}
photoFile?.also { file ->
val photoURI: Uri = FileProvider.getUriForFile(
this,
"com.example.android.provider",
file
)
cameraPhotoFilePath = photoURI
intent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI)
}
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
startActivityForResult(intent, ACTION_REQUEST_CAMERA)
Run Code Online (Sandbox Code Playgroud)
这是我在上面的代码中使用的辅助函数
@Throws(IOException::class)
private fun createImageFileInAppDir(): File {
val timeStamp: String = SimpleDateFormat("yyyyMMdd_HHmmss").format(Date())
val imagePath = getExternalFilesDir(Environment.DIRECTORY_PICTURES)
return File(imagePath, "JPEG_${timeStamp}_" + ".jpg")
}
Run Code Online (Sandbox Code Playgroud)
最后onActivityResult这就是我得到图像 Uri 的方式
if (resultCode == RESULT_OK && requestCode == ACTION_REQUEST_CAMERA) {
cameraPhotoFilePath?.let { uri ->
// here uri is image Uri that was captured by camera
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4781 次 |
| 最近记录: |