I am creating a drawing app and have added a save image functionality which will store my bitmap in the Pictures folder of external storage using MediaStore. Now I want to add a functionality of sharing image and for that absolute path of the saved image is needed. I am confused how to get the absolute path of the image.
P.S.- I have used the code of Philipp Lackner for saving image in external storage.
private fun saveImage(mbitmap:Bitmap?):Boolean/*String*/{ // to run code in Background Thread
val displayName = "Drawing" + System.currentTimeMillis() / 1000
val imageCollection = sdkVersion29andUp {
MediaStore.Images.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY)
} ?: MediaStore.Images.Media.EXTERNAL_CONTENT_URI
val contentValues = ContentValues().apply {
put(MediaStore.Images.Media.DISPLAY_NAME, "$displayName.jpeg")
put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg")
put(MediaStore.Images.Media.WIDTH, mbitmap!!.width)
put(MediaStore.Images.Media.HEIGHT, mbitmap!!.height)
}
return try{
contentResolver.insert(imageCollection,contentValues)?.also { uri ->
contentResolver.openOutputStream(uri).use { outputstream->
if(!mbitmap!!.compress(Bitmap.CompressFormat.JPEG,95,outputstream))
throw IOException("Couldn't save Bitmap")
}
}?: throw IOException("Couldn't create MediaStore entry")
true
}catch (e:IOException){
e.printStackTrace()
false
}
Below is the code for Share Image functionality.Here savedImagePath is the global variable for storing the absolute path of the saved Image.
private fun shareImage(){
MediaScannerConnection.scanFile(this,arrayOf(savedImagePath!!),null){
path,uri-> val sharedIntent=Intent()
sharedIntent.action=Intent.ACTION_SEND
sharedIntent.putExtra(Intent.EXTRA_STREAM,uri)
sharedIntent.setType("image/jpeg")
startActivity(
Intent.createChooser(sharedIntent,"Share")
)
}
}
You can get a file path from a content uri using this:
If you want a shorter version you can use only:
getFileRealPath()and that will give you the uri file path in case the uri is a content uri which is the case in the code you provided.P.S: the DATA column may be shown as deprecated, but it is still available to read from.