首先,需要引入 CameraX 和 CameraX 的生命周期组件库,可以在 build.gradle 中添加以下依赖项:
implementation "androidx.camera:camera-core:1.0.0-beta07"
implementation "androidx.camera:camera-lifecycle:1.0.0-beta07"
在布局文件中添加 ImageView 组件,用于显示拍照后的照片。
通过 CameraX 实现相机的预览和拍照功能,并将拍照后得到的照片转换为 Bitmap 格式:
// 创建一个 Preview 用于相机预览
val preview = Preview.Builder()
.setTargetRotation(viewFinder.display.rotation)
.build().also {
it.setSurfaceProvider(viewFinder.surfaceProvider)
}
// 创建一个 ImageCapture 用于拍照
val imageCapture = ImageCapture.Builder()
.setCaptureMode(ImageCapture.CAPTURE_MODE_MAXIMIZE_QUALITY)
.setTargetRotation(viewFinder.display.rotation)
.build()
// 将拍照后得到的照片转换为 Bitmap 格式
imageCapture.takePicture(ContextCompat.getMainExecutor(this), object : ImageCapture.OnImageCapturedCallback() {
override fun onCaptureSuccess(image: ImageProxy) {
val buffer = image.planes[0].buffer
val bytes = ByteArray(buffer.remaining())
buffer.get(bytes)
val bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.size)
imageView.post { imageView.setImageBitmap(bitmap) }
super.onCaptureSuccess(image)
}
override fun onError(exception: ImageCaptureException) {
super.onError(exception)
}
})
在代码中实例化 CameraX,并将 CameraX 组件绑定到生命周期:
// 初始化 CameraX
CameraX.bindToLifecycle(this, preview, imageCapture)
// 在 onDestroy() 方法中解绑 CameraX
CameraX.unbindAll()
完整代码示例:
class MainActivity : AppCompatActivity() {
private lateInite var viewFinder: TextureView
private lateInite var imageView: ImageView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
viewFinder = findViewById(R.id.view_finder)
imageView = findViewById(R.id.preview_image_view)
// 创建一个 Preview 用于相机预览
val preview = Preview.Builder()
.setTargetRotation(viewFinder.display.rotation)
.build().also {
it.setSurfaceProvider(viewFinder.surfaceProvider)
}
// 创建一个 ImageCapture 用于拍照
val imageCapture = ImageCapture.Builder()
.setCaptureMode(ImageCapture.CAPTURE_MODE_MAXIMIZE_QUALITY)
.setTargetRotation(viewFinder.display.rotation)
.build()
// 将拍照后得到的照片转换为 Bitmap 格式
imageCapture.takePicture(ContextCompat.getMainExecutor(this), object : ImageCapture.OnImageCapturedCallback() {
override fun onCaptureSuccess(image: ImageProxy) {
val buffer = image.planes[0].buffer
val bytes = ByteArray(buffer.remaining())
buffer.get(bytes)
val bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.size)