Save bitmap to location

前端 未结 19 2452
悲哀的现实
悲哀的现实 2020-11-22 00:20

I am working on a function to download an image from a web server, display it on the screen, and if the user wishes to keep the image, save it on the SD card in a certain fo

19条回答
  •  走了就别回头了
    2020-11-22 00:57

    I know this question is old, but now we can achieve the same result without WRITE_EXTERNAL_STORAGE permission. Instead of we can use File provider.

    private fun storeBitmap(bitmap: Bitmap, file: File){
            requireContext().getUriForFile(file)?.run {
                requireContext().contentResolver.openOutputStream(this)?.run {
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, this)
                    close()
                }
            }
        }
    

    How to retrieve file from provider ?

    fun Context.getUriForFile(file: File): Uri? {
            return FileProvider.getUriForFile(
                this,
                "$packageName.fileprovider",
                file
            )
        }
    

    Also do not forget register your provider in Android manifest

    
            
        
    

提交回复
热议问题