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
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.