You can copy image files to any other folder directory using Content Resolver from this function
fun copyImageFileToMediaStore(
context: Context,
sourceFilePath: String,
destinationFolder: File
) {
val sourceFile = File(sourceFilePath)
val extension = MimeTypeMap.getFileExtensionFromUrl(sourceFilePath)
val mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension)
val fileName = sourceFile.name
val inputStream = FileInputStream(sourceFile)
val resolver: ContentResolver = context.contentResolver
// Check if a file with the same name already exists in the destination folder
val projection = arrayOf(MediaStore.MediaColumns._ID)
val selection =
"${MediaStore.MediaColumns.DISPLAY_NAME} = ? AND ${MediaStore.MediaColumns.RELATIVE_PATH} = ? AND ${MediaStore.MediaColumns.DATA} = ?"
val selectionArgs = arrayOf(
fileName,
"${destinationFolder.path}/",
destinationFolder.absolutePath + File.separator + fileName
)
val cursor = resolver.query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
projection,
selection,
selectionArgs,
null
)
if (cursor != null && cursor.count > 0) {
// File already exists in the MediaStore, do not insert it again
cursor.close()
return
}
// File does not exist in the MediaStore, insert it
val values = ContentValues().apply {
put(MediaStore.MediaColumns.DISPLAY_NAME, fileName)
put(MediaStore.MediaColumns.MIME_TYPE, mimeType)
put(MediaStore.MediaColumns.RELATIVE_PATH, destinationFolder.parent)
put(
MediaStore.MediaColumns.DATA,
destinationFolder.absolutePath + File.separator + fileName
)
}
var outputStream: FileOutputStream? = null
var uri: Uri? = null
try {
val contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
uri = resolver.insert(contentUri, values)
if (uri == null) {
throw IOException("Failed to create new MediaStore record.")
}
outputStream = resolver.openOutputStream(uri) as FileOutputStream?
if (outputStream == null) {
throw IOException("Failed to get output stream.")
}
val buffer = ByteArray(4 * 1024)
var read: Int
while (inputStream.read(buffer).also { read = it } != -1) {
outputStream.write(buffer, 0, read)
}
outputStream.flush()
} catch (e: IOException) {
uri?.let { resolver.delete(it, null, null) }
uri = null
} finally {
inputStream.close()
outputStream?.close()
}
}
Call this function like this
val destinationFolder = File("/storage/emulted/0/DCIM/foldername")
val sourceFilePath = "/storage/emulted/0/DCIM/anyOtherFolder/abcd.jpeg"
copyImageFileToMediaStore(requireContext(), sourceFilePath, destinationFolder)