On a certain tap event, I ask the user to add an image. So I provide two options:
if you get image from camera there is no way to get Uri from a bitmap, so you should save your bitmap first.
launch camera intent
startActivityForResult(Intent(MediaStore.ACTION_IMAGE_CAPTURE), 8)
then, override
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (resultCode == Activity.RESULT_OK && requestCode == 8) {
val bitmap = data?.extras?.get("data") as Bitmap
val uri = readWriteImage(bitmap)
}
}
also create method to store bitmap and then return the Uri
fun readWriteImage(bitmap: Bitmap): Uri {
// store in DCIM/Camera directory
val dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM)
val cameraDir = File(dir, "Camera/")
val file = if (cameraDir.exists()) {
File(cameraDir, "LK_${System.currentTimeMillis()}.png")
} else {
cameraDir.mkdir()
File(cameraDir, "LK_${System.currentTimeMillis()}.png")
}
val fos = FileOutputStream(file)
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos)
fos.flush()
fos.close()
Uri.fromFile(file)
}
PS: dont forget to Add Permission and handle runtime permission (API >= 23)