Pick gallery photo move different file path in kotlin

Rmvivek
1 min readSep 19, 2023

1.we can choose distination path

private fun getOutputDirectory(): File {
val mediaDir = externalMediaDirs.firstOrNull()?.let {
File(it, resources.getString(R.string.app_name)).apply { mkdirs() }
}
return if (mediaDir != null && mediaDir.exists())
mediaDir else filesDir
}
//assign path to variable
outputDirectory = getOutputDirectory()
string file <string name="app_name">rmpicker</string>

2. open pick app

pickMedia.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly))
val pickMedia = registerForActivityResult(ActivityResultContracts.PickVisualMedia()) { uri ->
if (uri != null) {
val FILENAME_FORMAT = "yyyy-MM-dd-HH-mm-ss-SSS"
val name = SimpleDateFormat(FILENAME_FORMAT, Locale.getDefault()).format(System.currentTimeMillis())
val photoFile = File(outputDirectory, "rmpick_${name}" + ".jpg")
getMoveFileToAppFolder(File(getPathFromURI(uri!!)), photoFile)
} else {
Log.e("PhotoPicker", "No media selected")
}
}

3. create file path

val pickMedia = registerForActivityResult(ActivityResultContracts.PickVisualMedia()) { uri ->
if (uri != null) {
val FILENAME_FORMAT = "yyyy-MM-dd-HH-mm-ss-SSS"
val name = SimpleDateFormat(FILENAME_FORMAT, Locale.getDefault()).format(System.currentTimeMillis())
val photoFile = File(outputDirectory, "rmpick_${name}" + ".jpg")
getMoveFileToAppFolder(File(getPathFromURI(uri!!)), photoFile)
} else {
Log.e("PhotoPicker", "No media selected")
}
}
fun getPathFromURI(contentUri: Uri?): String? {
var res: String? = null
val proj = arrayOf(MediaStore.Images.Media.DATA)
val cursor = contentResolver.query(contentUri!!, proj, null, null, null)
if (cursor!!.moveToFirst()) {
val column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA)
res = cursor.getString(column_index)
}
cursor.close()
return res
}
@Throws(IOException::class)
private fun getMoveFileToAppFolder(sourceFile: File, destFile: File) {
if (!sourceFile.exists()) {
return
}
var source: FileChannel? = null
var destination: FileChannel? = null
source = FileInputStream(sourceFile).getChannel()
destination = FileOutputStream(destFile).getChannel()
if (destination != null && source != null) {
destination.transferFrom(source, 0, source.size())
}
source?.close()
destination?.close()
}

--

--