我想拍摄一张照片,并使用 CameraX 从中心裁剪出一个 25x25 dp 的正方形。我读到可以使用 ImageCapture 进行裁剪,但不幸的是到目前为止几乎没有类似的示例。
val imageCaptureConfig = ImageCaptureConfig.Builder().apply {
setTargetAspectRatio(Rational(1, 1))
setCaptureMode(ImageCapture.CaptureMode.MIN_LATENCY)
}.build()
val imageCapture = ImageCapture(imageCaptureConfig)
btn_take_photo.setOnClickListener {
imageCapture.takePicture(
object : ImageCapture.OnImageCapturedListener() {
override fun onCaptureSuccess(image: ImageProxy?, rotationDegrees: Int) {
super.onCaptureSuccess(image, rotationDegrees)
// image manipulation here?
}
}
)
}
最佳答案
您可以使用此功能在捕获图像后裁剪图像:
private fun cropImage(bitmap: Bitmap, frame: View, reference: View): ByteArray {
val heightOriginal = frame.height
val widthOriginal = frame.width
val heightFrame = reference.height
val widthFrame = reference.width
val leftFrame = reference.left
val topFrame = reference.top
val heightReal = bitmap.height
val widthReal = bitmap.width
val widthFinal = widthFrame * widthReal / widthOriginal
val heightFinal = heightFrame * heightReal / heightOriginal
val leftFinal = leftFrame * widthReal / widthOriginal
val topFinal = topFrame * heightReal / heightOriginal
val bitmapFinal = Bitmap.createBitmap(
bitmap,
leftFinal, topFinal, widthFinal, heightFinal
)
val stream = ByteArrayOutputStream()
bitmapFinal.compress(
Bitmap.CompressFormat.JPEG,
100,
stream
) //100 is the best quality possibe
return stream.toByteArray()
}
裁剪图像,引用 View 父级(如框架)和 View 子级(如最终引用)
- 参数
位图
要裁剪的图像 - param
frame
设置图像的位置 - param
reference
引用帧来裁剪图像 返回
已裁剪的图像
关于Android:如何使用 CameraX 裁剪图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57222800/