简体   繁体   中英

How to save image from URL to local and get it's Uri?

I have the following code -

 verifyOtpViewModel.userData.observe(this, Observer {
            if (it == null) return@Observer
            if (it.profileImage != null) {
                ...
            }
}

profileImage is my image URL.

I need an updated way, by 2020 standard to get the image bitmap from the URL and then get the URI from that bitmap.

All answers on this subject use the soon-to-be deprecated AsyncTask and I was hoping for a better solution, maybe a 3rd party library even.

Thanks!

First download the image if it's not already downloaded

GlideApp is the generated API:

Add a class with exact same name. Be sure to Rebuild after adding this code snippet:

you need to use kapt instead of annotactionProccesser on Kotlin.

@GlideModule
class MyAppGlideModule : AppGlideModule()

diskCacheStrategy(DiskCacheStrategy.NONE) don't let Glide cache this image. Target.Size_Original keep the original size when you download the image from url.

GlideApp
            .with(context)
            .asBitmap()
            .load(uri)
            .diskCacheStrategy(DiskCacheStrategy.NONE)
            .into(object : CustomTarget<Bitmap>(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL) {
                override fun onLoadCleared(placeholder: Drawable?) {}
                override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>?) {
                       //Save image file
                       saveFile(resource)
                       //Load into imageview if needed
                    }
                }
            })

Save the image file. It's recommended to use background threads for this.

val randomFilename = //generate a name based on your preferences
val file = File(saveDirectory, randomFilename)
val fos = FileOutputStream(file)
val bos = BufferedOutputStream(fos)
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos)
bos.close()

Update your room database with the name of the file to retrieve that later.

@Query("UPDATE table_name SET image_filename = :fileName WHERE id = :id ")
fun updateImageFilename(id: Int, filename: String)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM