How can I save an image from a url?

后端 未结 5 1135
情深已故
情深已故 2020-12-17 05:53

I\'m setting an ImageView using setImageBitmap with an external image url. I would like to save the image so it can be used later on even if there is no interne

5条回答
  •  猫巷女王i
    2020-12-17 06:23

    If you are using Kotlin and Glide in your app then this is for you:

    Glide.with(this)
                    .asBitmap()
                    .load(imageURL)
                    .into(object : SimpleTarget(1920, 1080) {
                        override fun onResourceReady(bitmap: Bitmap, transition: Transition?) {
                            saveImage(bitmap)
                        }
                    })
    

    and this is that function

    internal fun saveImage(image: Bitmap) {
        val savedImagePath: String
    
        val imageFileName = System.currentTimeMillis().toString() + ".jpg"
        val storageDir = File(Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_PICTURES).toString() + "/Folder Name")
        var success = true
        if (!storageDir.exists()) {
            success = storageDir.mkdirs()
        }
        if (success) {
            val imageFile = File(storageDir, imageFileName)
            savedImagePath = imageFile.absolutePath
            try {
                val fOut = FileOutputStream(imageFile)
                image.compress(Bitmap.CompressFormat.JPEG, 100, fOut)
                fOut.close()
            } catch (e: Exception) {
                e.printStackTrace()
            }
    
            galleryAddPic(savedImagePath)
        }
    }
    
    
    private fun galleryAddPic(imagePath: String) {
        val mediaScanIntent = Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE)
        val f = File(imagePath)
        val contentUri = FileProvider.getUriForFile(applicationContext, packageName, f)
        mediaScanIntent.data = contentUri
        sendBroadcast(mediaScanIntent)
    }
    

    galleryAddPic() is used to see the image in a phone gallery.

    Note: now if you face file uri exception then this can help you.

提交回复
热议问题