无法使用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 }
}

根据我在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)
}
})

}

但是,当我单击按钮捕获并保存图像时,我会收到以下错误消息: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()
.
.
.
.
.
.

我不确定问题出在哪里,我们将不胜感激。

更新:很明显,问题是由于CameraX API CameraX 1.0.0-beta09和camera扩展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
)

最新更新