首页 > 解决方案 > 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 将照片保存在此。我检查了照片是否正确拍摄。

标签: androidkotlinandroid-imagegoogle-mlkit

解决方案


推荐阅读