【发布时间】:2022-01-06 21:17:53
【问题描述】:
我正在关注一些 camerax 教程,并且我正在尝试让图像捕获和保存工作,但是永远不会调用 'onImageSaved' 函数,即使我可以得到图像位置的 Uri,它不指向任何内容。我花了几个小时试图调试它,但无法弄清楚出了什么问题。 我试过检查文件访问权限,这不是问题。
private fun takePhoto(){
// Get a stable reference of the modifiable image capture use case
val imageCapture = imageCapture ?: return
// Create time-stamped output file to hold the image
//val photoFile = File(externalMediaDirs[0],"JPEG_${System.currentTimeMillis()}.jpg")
val directory: File = applicationContext.getDir("imageDir", Context.MODE_PRIVATE)
val photoFile = File(directory, "JPEG_${System.currentTimeMillis()}.jpg")
// Create output options object which contains file + metadata
val outputOptions = ImageCapture.OutputFileOptions.Builder(photoFile).build()
// Convert filepath to Uri
val imageUri = Uri.fromFile(photoFile)
// Set up image capture listener, which is triggered after photo has been taken
imageCapture.takePicture(
outputOptions, ContextCompat.getMainExecutor(this), object : ImageCapture.OnImageSavedCallback {
override fun onError(exc: ImageCaptureException) {
Log.e(TAG, "Photo capture failed: ${exc.message}", exc)
}
override fun onImageSaved(output: ImageCapture.OutputFileResults) {
// TODO This never runs
val msg = "Photo capture succeeded: $imageUri"
Toast.makeText(baseContext, msg, Toast.LENGTH_SHORT).show()
Log.d(TAG, msg)
}
})
// Send our image Uri back to the demo app & finish this activity
val intent = Intent()
intent.putExtra("ImageUri", imageUri)
runOnUiThread {
setResult(2, intent)
finish()
}
}
【问题讨论】:
-
你好,伙计,我面临着同样的问题,它发生在 android 10 中,在 adnroid 11 中它的工作非常适合你可以点击 a=image 然后保存位图 int 文件
标签: android android-studio kotlin android-camerax