imagekotlincopymovewritetofile

Kotlin : copy image to gallery


I am trying to copy an image that is stored in my application folder to a predefined folder in my gallery.

I started from an image sharing code..

This is my code :

val extension = when (requireNotNull(pictureResult).format) {
                PictureFormat.JPEG -> "jpg"
                PictureFormat.DNG -> "dng"
                else -> throw RuntimeException("Unknown format.")
}
val timestamp = System.currentTimeMillis()  
val namePhoto = "picture_"+timestamp+"."+extension;
val destFile = File(filesDir, namePhoto)
val folder = "/CustomFolder"

CameraUtils.writeToFile(requireNotNull(pictureResult?.data), destFile) { file ->
            if (file != null) {

                // Code to share - it works
                /*
                val context = this@PicturePreviewActivity
                val intent = Intent(Intent.ACTION_SEND)
                intent.type = "image/*"
                val uri = FileProvider.getUriForFile(context, context.packageName + ".provider", file)
                intent.putExtra(Intent.EXTRA_STREAM, uri)
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
                startActivity(intent)
                */
                */

                // Code to save image to gallery - doesn't work :(
                val photoDirectory = File(Environment.DIRECTORY_PICTURES+folder, namePhoto)
                val sourcePath = Paths.get(file.toURI())
                Log.i("LOG","sourcePath : "+sourcePath.toString()) // /data/user/0/com.app.demo/files/picture_1663772068143.jpg
                val targetPath = Paths.get(photoDirectory.toURI())
                Log.i("LOG","targetPath : "+targetPath.toString()) // /Pictures/CustomFolder/picture_1663772068143.jpg
                Files.move(sourcePath, targetPath, StandardCopyOption.REPLACE_EXISTING)

                // Error here but I don't know why

                
            } else {
                Toast.makeText(this@PicturePreviewActivity, "Error while writing file.", Toast.LENGTH_SHORT).show()
            }
        }

How do I copy the image to a predefined folder?


Solution

  • Ok, I did it !

    Solution :

    val folder = "/CustomFolder/"  // name of your folder
    val timestamp = System.currentTimeMillis()          
    val namePicture = "picture_"+timestamp+"."+extension; 
    
    try {
         val path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES+folder);
    
         if (!path.exists()) {
             path.mkdir();
         }
    
         val pathImage =  File(path,namePicture)
         val stream = FileOutputStream(pathImage)
         stream.write(imageByteArray).run {
              stream.flush()
              stream.close()
         }
    
    } catch (e: FileNotFoundException) {
        e.printStackTrace()
    }