Insert Video to gallery [Android Q]

后端 未结 2 1340
栀梦
栀梦 2021-01-03 01:42

To record a SurfeceView I\'m using a 3rd-party library , this library requires a path where the output (the recorded video) saved in my case is savedVid

2条回答
  •  [愿得一人]
    2021-01-03 02:20

    Here it is my solution - save photo/video to Gallery.

    private fun saveMediaFile2(filePath: String?, isVideo: Boolean, fileName: String) {
    filePath?.let {
        val context = MyApp.applicationContext
        val values = ContentValues().apply {
            val folderName = if (isVideo) {
                Environment.DIRECTORY_MOVIES
            } else {
                Environment.DIRECTORY_PICTURES
            }
            put(MediaStore.Images.Media.DISPLAY_NAME, fileName)
            put(MediaStore.Images.Media.MIME_TYPE, MimeUtils.guessMimeTypeFromExtension(getExtension(fileName)))
            put(MediaStore.Images.Media.RELATIVE_PATH, folderName + "/${context.getString(R.string.app_name)}/")
            put(MediaStore.Images.Media.IS_PENDING, 1)
        }
    
        val collection = if (isVideo) {
            MediaStore.Video.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY)
        } else {
            MediaStore.Images.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY)
        }
        val fileUri = context.contentResolver.insert(collection, values)
    
        fileUri?.let {
            if (isVideo) {
                context.contentResolver.openFileDescriptor(fileUri, "w").use { descriptor ->
                    descriptor?.let {
                        FileOutputStream(descriptor.fileDescriptor).use { out ->
                            val videoFile = File(filePath)
                            FileInputStream(videoFile).use { inputStream ->
                                val buf = ByteArray(8192)
                                while (true) {
                                    val sz = inputStream.read(buf)
                                    if (sz <= 0) break
                                    out.write(buf, 0, sz)
                                }
                            }
                        }
                    }
                }
            } else {
                context.contentResolver.openOutputStream(fileUri).use { out ->
                    val bmOptions = BitmapFactory.Options()
                    val bmp = BitmapFactory.decodeFile(filePath, bmOptions)
                    bmp.compress(Bitmap.CompressFormat.JPEG, 90, out)
                    bmp.recycle()
                }
            }
            values.clear()
            values.put(if (isVideo) MediaStore.Video.Media.IS_PENDING else MediaStore.Images.Media.IS_PENDING, 0)
            context.contentResolver.update(fileUri, values, null, null)
        }
    }
    }
    

提交回复
热议问题