android - Android如何创建具有正确方向的位图图像?
问题描述
我正在开发一个使用 mlkit 检测图像中身份证的项目。输出是一个只有身份证的裁剪图像。当我从给定图像文件的 uri 创建输入位图时,输入位图的方向错误。
var inputBitmapWithWrongOrientation1: Bitmap = MediaStore.Images.Media.getBitmap(requireContext().contentResolver, inputUri)
// var inputBitmapWithWrongOrientation2: Bitmap = BitmapFactory.decodeFile(photoFile.path)
据我所知,输入文件以正确的方向(即0度)保存。所以无论你做什么 ( ExifInterFace
, MediaStore contentresolver query
) 他们都会返回 0 度。MlKit 读取输入 uri 并以正确的方向处理所有内容。所以detectedObject.boundaryBox 是正确的。但 inputBitmapWithWrongOrientation1 方向错误(90 或 270 度)。因此,尝试使用该边界框裁剪 inputBitmapWithWrongOrientation1 会裁剪图像的错误部分。
结果,inputBitmapWithWrongOrientation1
总是处于错误的方向(90 度或 270 度方向)。
如何获得具有正确方向的 inputBitmap?相关代码段:
val inputBitmap: Bitmap = getBitmapWithCorrectOrientation(inputUri) // <-- what should be this?
val inputImage: InputImage = InputImage.fromFilePath(contentResolver, inputUri) // for mlkit
objectDetector.process(inputImage).addOnSuccessListener { detectedObjectsList ->
Log.e(TAG, "detectedObjectsList.size = ${detectedObjectsList.size}")
for(detectedObject in detectedObjectsList) {
val bBox = detectedObject.boundingBox
val outputBitmap = Bitmap.createBitmap(inputBitmap, bBox.left, bBox.top, bBox.width(), bBox.height())
outputIv.setImageBitmap(outputBitmap)
}
}
编辑
我从 CameraX 获取图像 uri:
val photoFile = File(requireContext().getExternalFilesDir(""), SimpleDateFormat(FILENAME_FORMAT, Locale.US
).format(System.currentTimeMillis()) + ".jpg") // <-- this is the captured image / input image save location
// create output options object which contains file + metadata
val outputOptions = ImageCapture.OutputFileOptions.Builder(photoFile).build()
imageCapture.takePicture(
outputOptions, ContextCompat.getMainExecutor(requireContext()),
object : ImageCapture.OnImageSavedCallback{
override fun onImageSaved(outputFileResults: ImageCapture.OutputFileResults) {
var inputUri = outputFileResults.savedUri
// then the rest of the code below
}
}
// ... ...
)
如您所见,图片是一个.jpg
保存在photoFile
. CameraX 将照片保存在此。我检查了照片是否正确拍摄。
解决方案
推荐阅读
- neural-network - 如何在 PyTorch 中仅在某些时候忽略损失
- python - 读取python数据框,一列表示为字符串
- spring-boot - Spring Boot - JPA 规范返回的展平 JSON 实体以导出到 excel
- python - Python 问题创建定义以合并两个数据集 - 使用字符串来引用和 vars()
- node.js - 猫鼬回调不执行
- salesforce - Lightning Experience 专家 - 步骤 6 - 无法完成
- spring - https//recipe-010-webhook.herokuapp.com?op=webhook .Error - Invalid URI: The URI scheme is not valid
- angular - angular 9 数组在订阅方法中为空
- excel - 将 Excel 值传递给同一类的多个方法
- javascript - JS倒数计时器停止在0