Mas*_*son 4 android kotlin android-camerax
我正在关注有关如何在 Android 上使用 CameraX API 的此代码实验室示例链接,但是当我尝试捕获图像并将其保存到在主活动的 Oncreate 方法中创建的外部媒体目录时,我收到一条错误消息:无法将捕获结果保存到指定位置
下面是创建目录的方法,在 Oncreate 方法中调用:
private fun getOutputDirectory(): File {
val mediaDir = externalMediaDirs.firstOrNull()?.let {
File(it, resources.getString(R.string.app_name)).apply { mkdirs() } }
return if (mediaDir != null && mediaDir.exists())
{ Log.i(TAG, mediaDir.path); mediaDir } else { filesDir }
}
Run Code Online (Sandbox Code Playgroud)
根据我在 Android 文档中阅读的内容,externalMediaDirs
在外部存储中创建了一个文件夹,虽然我的手机没有外部存储,但该文件夹已在此路径下成功创建:/storage/emulated/0/Android/media/com.example.camerax/cameraX
然后当点击拍照图像按钮时调用此方法:
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(
outputDirectory,
SimpleDateFormat(FILENAME_FORMAT, Locale.US
).format(System.currentTimeMillis()) + ".jpg")
// Create output options object which contains file + metadata
val outputOptions = ImageCapture.OutputFileOptions.Builder(photoFile).build()
// 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) {
val savedUri = Uri.fromFile(photoFile)
val msg = "Photo capture succeeded: $savedUri"
Toast.makeText(baseContext, msg, Toast.LENGTH_SHORT).show()
Log.d(TAG, msg)
}
})
}
Run Code Online (Sandbox Code Playgroud)
但是,当我单击按钮捕获并保存图像时,收到此错误消息: ImageCaptureException:“无法将捕获结果保存到指定位置”
我试过的:
我试图创建一个应用程序本地的文件夹并将图像保存在那里,它工作正常,我使用了这种方法:
private fun takePhoto() {
.
.
.
folder: File = File(getFilesDir(), "testFolder");
if (!file.exists()) {
file.mkdir();
}
testImage = File(folder, "test.jpg");
val outputOptions = ImageCapture.OutputFileOptions.Builder(testImage).build()
.
.
.
.
.
.
Run Code Online (Sandbox Code Playgroud)
我不确定可能是什么问题,任何帮助表示赞赏。
更新: 显然这个问题是由于 CameraX API CameraX 1.0.0-beta09 和 camera-extension 1.0.0-alpha16 中的一个错误造成的。当使用 CameraX 1.0.0-beta08 和相机扩展 1.0.0-alpha15 时,它工作正常。
这是 CameraX 1.0.0-beta09 中的一个错误。它已被修补,可能会在下一个版本中提供。
它崩溃是因为您尝试将其保存到的文件实际上并未创建。作为一种解决方法,使用File.createTempFile()
,它会在目录中创建一个空文件。
val photoFile = File.createTempFile(
SimpleDateFormat(FILENAME_FORMAT, Locale.US).format(System.currentTimeMillis()),
".jpg",
outputDirectory
)
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1551 次 |
最近记录: |