android - Android CameraX 图像旋转
问题描述
我已经按照 Google CameraX代码实验室来实现自定义相机。相机预览很好,但是当我在图像捕获图像旋转后拍摄图像时。我正在以纵向模式拍摄图像,但保存的图像是横向的。这是配置相机的方法
private fun startCamera() {
val cameraProviderFuture = ProcessCameraProvider.getInstance(this)
cameraProviderFuture.addListener(Runnable {
// Used to bind the lifecycle of cameras to the lifecycle owner
val cameraProvider: ProcessCameraProvider = cameraProviderFuture.get()
// Preview
val preview = Preview.Builder()
.setTargetRotation(this.windowManager.defaultDisplay.rotation)
.build()
.also {
it.setSurfaceProvider(viewFinder.createSurfaceProvider())
}
imageCapture = ImageCapture.Builder()
.setTargetRotation(this.windowManager.defaultDisplay.rotation)
.build()
val imageAnalyzer = ImageAnalysis.Builder()
.build()
.also {
it.setAnalyzer(cameraExecutor, LuminosityAnalyzer { luma ->
Log.d(TAG, "Average luminosity: $luma")
})
}
// Select back camera as a default
val cameraSelector = CameraSelector.DEFAULT_BACK_CAMERA
try {
// Unbind use cases before rebinding
cameraProvider.unbindAll()
// Bind use cases to camera
cameraProvider.bindToLifecycle(
this, cameraSelector, preview, imageCapture, imageAnalyzer)
} catch(exc: Exception) {
Log.e(TAG, "Use case binding failed", exc)
}
}, ContextCompat.getMainExecutor(this))
}
这是捕获图像的方法:
private fun takePhoto() {
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"
val bitmap = MediaStore.Images.Media.getBitmap(contentResolver, savedUri)
ivCapturedImage.setImageBitmap(bitmap)
setCaptureUI(false)
Log.d(TAG, msg)
}
})
}
使用EXIF拍摄后我需要自己旋转图像还是可以在配置相机时修复它?
解决方案
默认情况下,ImageCapture 将捕获的方向设置为显示旋转。如果图像保存到磁盘,旋转将在 EXIF 中。
您的设备是否处于锁定纵向模式?在这种情况下,显示旋转与设备的方向不匹配,您需要自己设置目标旋转。例子。
// The value is whatever the display rotation should be, if the device orientation is not locked.
imageCapture.setTargetRotation(...)
或者,您可以简单地使用LifecycleCameraController API。它为您处理轮换,并以所见即所得的方式使所有用例保持一致。
推荐阅读
- javascript - 复选框过滤器/搜索按钮:未选中时无法撤消过滤
- php - 调度程序 runInBackground 在 laravel 5.4 中不起作用
- xml - Odoo 10:布尔字段旁边的输入字段
- sql - 将 SSIS 参数传递给 OPENQUERY
- android - 如何在单独的 UI 活动中检索 Firebase 任务结果
- python - 使用 Python 和 Node.js 在 Heroku 中导入 psycopg2
- javascript - 如何用按钮控制背景音乐?
- matlab - 根据向量定义的间隔更改while循环
- c - 如何覆盖C中的部分字符串?
- rpm - 安装安装要求 RPM 规范