Home > Software design >  How do I get the actual image taken from a camera in Android Studio?
How do I get the actual image taken from a camera in Android Studio?

Time:04-22

I am taking a photo using the camera in Android Studio and I would like to save the actual image that resulted from the action. I can access the URI just fine but I would like the actual image itself, as I need to send the photo to a database.

    var image_uri: Uri? = null
    lateinit var bitmap: Bitmap
    
    private fun openCamera() {
        val resolver = requireActivity().contentResolver
        val values = ContentValues()
        values.put(MediaStore.Images.Media.TITLE, "New Picture")
        values.put(MediaStore.Images.Media.DESCRIPTION, "From the Camera")
        image_uri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values)

        bitmap = MediaStore.Images.Media.getBitmap(resolver, image_uri)

        val cameraIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
        cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, image_uri)
        startActivityForResult(cameraIntent, IMAGE_CAPTURE_CODE)
    }

I have read that the easiest way to do this is to create a bitmap but I can not get that to work. Running my overall program, the application crashes whenever openCamera is even called. If I comment out the bitmap line, then the function works fine (except I don't have the file saved like I want). How can I do this to where bitmap is an actual Bitmap Object that I can send to the backend of my program?

CodePudding user response:

Easiest way to get the Bitmap is in onActivityResult() like val imageBitmap = data.extras.get("data") as Bitmap. I suggest looking at the documentation for camera, maybe you'll find something useful here.

CodePudding user response:

You can get image bitmap from Camera with this way:

// Open camera
val cameraIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
resultLauncher.launch(cameraIntent)

// Get your image
private val resultLauncher =
    registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
        if (result.resultCode == Activity.RESULT_OK) {
            if (result?.data != null) {
                bitmap = result.data?.extras?.get("data") as Bitmap
            }
        }
    }
  • Related