ChandrimG
ChandrimG

Reputation: 147

Error in capture image and save in gallery in Android API level 27 using CameraX API

I am trying to capture image and save it in a file using cameraX Api

val name = "CameraxImage.jpeg"
val contentValues = ContentValues().apply {
    put(DISPLAY_NAME, name)
    put(MIME_TYPE, "image/jpeg")
        put(Images.Media.RELATIVE_PATH, "Pictures/CameraX-Image")
}
val outputOptions = ImageCapture.OutputFileOptions
    .Builder(
        context.contentResolver,
        Images.Media.EXTERNAL_CONTENT_URI,
        contentValues
    )
    .build()
imageCapture.takePicture(
    outputOptions,
    ContextCompat.getMainExecutor(context),
    object : ImageCapture.OnImageSavedCallback {
        override fun onImageSaved(outputFileResults: ImageCapture.OutputFileResults) {
            val bitmapImage = outputFileResults.savedUri?.let {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                    ImageDecoder.decodeBitmap(ImageDecoder.createSource(context.contentResolver, it))
                } else {
                    Images.Media.getBitmap(context.contentResolver, it)
                }
            }
            if (bitmapImage != null) {
                rotateImageIfRequired(outputFileResults.savedUri!!, context, bitmapImage)
                onPhotoCaptured(cropImage(bitmapImage, croppedRect, parentFrame))
            }
        }

        override fun onError(exception: ImageCaptureException) {
            Log.d(TAG, "onError: ${exception.message}")
        }
    })

This code works well in Android API 30. But throw following error when try to capture in API level 27 and 25.

onError: Failed to insert a MediaStore URI.

Alternative to MediaStore.getBitmap() works in API 29. How to capture and save image in API 27 and 25?

Upvotes: 0

Views: 23

Answers (0)

Related Questions