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?
3
Answers
Easiest way to get the Bitmap is in
onActivityResult()
likeval imageBitmap = data.extras.get("data") as Bitmap
. I suggest looking at the documentation for camera, maybe you’ll find something useful here.You can get image bitmap from Camera with this way:
The way to get the actual image would be to pass the file object, you want to store the image at, to the intent – and that is where the full size image will be.
according to android developers documentation
you should create the file (assuming you’ve got the READ_EXTERNAL_STORAGE and WRITE_EXTERNAL_STORAGE permissions depending on the android version and the location of the file you create…) and then pass the file to intent
}
In the code snippet it refers to a method "createImageFile()" where the file is being created (The docs in the link provides some samples).