Reputation: 1
How can we save image file in DCIM folder using MediaStore API ?
private fun savePhotoToExternalStorage(displayName: String, bmp: Bitmap): Boolean {
val imageCollection = sdk29AndUp {
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.jpg")
put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg")
put(MediaStore.Images.Media.WIDTH, bmp.width)
put(MediaStore.Images.Media.HEIGHT, bmp.height)
}
return try {
contentResolver.insert(imageCollection, contentValues)?.also { uri ->
Log.e("file path", File(uri.path.toString()).absolutePath)
contentResolver.openOutputStream(uri).use { outputStream ->
if (!bmp.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
}
}
in above code, my file is saved in Pictures Directory. but i want it in DCIM Directory for both above and below SDK version 29.
Upvotes: 0
Views: 1233
Reputation: 1183
Please try this way to save image
fun saveImnage(
context: Context,
bmap: Bitmap,
name: String
): File? {
val file = File(
context.getExternalFilesDir(Environment.DIRECTORY_DCIM),
"$name.jpeg"
)
val outStream: FileOutputStream
try {
outStream = FileOutputStream(file)
bmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream)
outStream.flush()
outStream.close()
} catch (e: FileNotFoundException) {
e.printStackTrace()
} catch (e: IOException) {
e.printStackTrace()
}
return file
}
hope it may help you
Upvotes: 1