how to save image in cache? - android

I want to when user is offline, the image from firebase storage that retrived in an imageview when he/she was online, be visible, but I can't implement that codes, as a beginner in android studio and kotlin.
I want add Glide image cache and loader to this :
private fun getUserProfile() {
val navigationView = binding.navView
val header: View = navigationView.getHeaderView(0)
storageReference = FirebaseStorage.getInstance().reference.child("Users/$uid")
val localeFile = File.createTempFile("tempFile","")
storageReference.getFile(localeFile).addOnSuccessListener {
val bitmap = BitmapFactory.decodeFile(localeFile.absolutePath)
val imageView = header.findViewById<ImageView>(R.id.circleImageView)
imageView.setImageBitmap(bitmap)
}.addOnFailureListener{
finish()
}
}
but I don't know how to add below codes to above one correctly :
Glide.with(this)
.load(url)
.into(imageView);
I added like below but in offline still not load :
private fun getUserProfile() {
val navigationView = binding.navView
val header: View = navigationView.getHeaderView(0)
storageReference = FirebaseStorage.getInstance().reference.child("Users/$uid")
val localeFile = File.createTempFile("tempFile","")
storageReference.getFile(localeFile).addOnSuccessListener {
val bitmap = BitmapFactory.decodeFile(localeFile.absolutePath)
val imageView = header.findViewById<ImageView>(R.id.circleImageView)
Glide.with(this)
.load(bitmap)
.into(imageView)
}.addOnFailureListener{
finish()
}
}

Related

How to to check if Coil ImageRequest is complete before returning the bitmap value

I'm trying to return the bitmap value from a lambda function but I get the error: lateinit property bitmap has not been initialized ... Is there a way to check if the ImageRequest is complete before returning the bitmap?
fun getBitmap(context:Context,imageUrl: String) : Bitmap{
lateinit var bitmap: Bitmap
val imageRequest = ImageRequest.Builder(context)
.data(imageUrl)
.target { drawable ->
bitmap = drawable.toBitmap() // This is the bitmap 🚨
}
.build()
ImageLoader(context).enqueue(imageRequest)
return bitmap
}
Hm... I don't have much time to explain. Just see the code and understand.
You have to use execute() instead of enqueue(). See
private suspend fun getBitmap(context: Context, url: String): Bitmap? {
var bitmap: Bitmap? = null
val request = ImageRequest.Builder(context)
.data(url)
.target(
onStart = {
Log.d(TAG, "Coil loader started.")
},
onSuccess = { result ->
Log.e(TAG, "Coil loader success.")
bitmap = result.toBitmapOrNull() // Or (result as BitmapDrawable).bitmap
},
onError = {
Log.e(TAG, "Coil loading error")
}
)
.build()
context.imageLoader.execute(request)
return bitmap
}

Download SVG data image with FirebaseStored

I want to download an image in svg that is in the FirebaseStore, using data method, but the bitmap conversion returns null.
I need returns the svg image and put on the screen
private lateinit var auth: FirebaseAuth
private lateinit var storage: FirebaseStorage
private lateinit var storageRef: StorageReference
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
auth = Firebase.auth
storage = Firebase.storage
storageRef = storage.reference
val fileRef = storageRef.child("CFM/cfm2.back.svg")
downloadImgData(fileRef)
}
private fun downloadImgData(fileRef: StorageReference?){
if (fileRef != null) {
val ONE_MEGABYTE = (1024 * 1024).toLong()
fileRef.getBytes(ONE_MEGABYTE)
.addOnSuccessListener { bytes ->
val bmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.size)
imageView.setImageBitmap(bmp)
textview.text = fileRef.name
}
.addOnFailureListener { exception ->
Toast.makeText(this, exception.message, Toast.LENGTH_LONG).show()
}
}
You can use Pixplicity's Sharp for loading SVG images into ImageView.
It provides method to load svg image from InputStream into ImageView.
ByteArray obtained from Firebase Storage can be converted to InputStream by calling bytes.inputStream().
Add the library dependency
dependencies {
implementation 'com.pixplicity.sharp:library:[VERSION_HERE]#aar'
}
This loads the SVG image to imageView
val stream = bytes.inputStream()
Sharp.loadInputStream(stream).into(imageView)
stream.close()
Finally the function looks like,
private fun downloadImgData(fileRef: StorageReference?) {
if (fileRef != null) {
val ONE_MEGABYTE = (1024 * 1024).toLong()
fileRef.getBytes(ONE_MEGABYTE)
.addOnSuccessListener { bytes ->
val stream = bytes.inputStream()
Sharp.loadInputStream(stream).into(imageView)
stream.close()
textview.text = fileRef.name
}
.addOnFailureListener { exception ->
Toast.makeText(this, exception.message, Toast.LENGTH_LONG).show()
}
}
}

Cannot load image from URI using picasso

I a having a problem in load picture in an imageview through uri. I am using picasso and my code is as below:
I have an object CreateImage with a function displayImageFromURI
fun displayImageFromURI(imageView: ImageView,uri: Uri?,context: Context){
Log.e("url", uri.toString())
Picasso.get()
.load(uri)
.fit().centerCrop()
.into(imageView, object: com.squareup.picasso.Callback {
override fun onSuccess() {
val imageBitmap = (imageView.drawable as BitmapDrawable).bitmap
val imageDrawable =
RoundedBitmapDrawableFactory.create(context.resources, imageBitmap)
imageView.setImageDrawable(imageDrawable)
}
override fun onError(e: java.lang.Exception?) {
Log.e("error",e.toString())
}
})
}
I am calling this function from a fragment as below:
if (!photoUrl.equals("")) {
Log.e("in photo url", photoUrl)
val image = Uri.parse(photoUrl)
CreateImage.displayImageFromURI(ivUploadQuestionImage, image, this)
}
but my image is not being loaded in the imageview. The string photoUrl contains the link in string format as well. Can anybody please help me?

How to get all bitmaps from animated webp using android fresco?

How to get a list of all bitmaps from webp animation using android fresco?
The code below is always returns null instead of a bitmap
val imageRequest = ImageRequestBuilder
.newBuilderWithSource(Uri.parse("https://upload.wikimedia.org/wikipedia/commons/4/41/Sunflower_from_Silesia2.jpg"))
.build()
val imagePipeline = Fresco.getImagePipeline()
val dataSource = imagePipeline.fetchDecodedImage(imageRequest, this)
dataSource.subscribe(object : BaseBitmapDataSubscriber() {
override fun onFailureImpl(dataSource: DataSource<CloseableReference<CloseableImage>>?) {
val m = dataSource
}
override fun onNewResultImpl(bitmap: Bitmap?) {
val m = bitmap
}
}, CallerThreadExecutor.getInstance())
For all interested, fresco docs has this line "This subscriber doesn’t work for animated images as those can not be represented as a single bitmap."

Convert Image from RecyclerView to Bitmap

I need to send a specific image from my recyclerview that has been clicked to the new activity that will display the image. The question is how do I convert my image to bitmap or something like that so I can send them using intent?
Here's my code:
RecyclerViewAdapter.kt
class ViewHolder(view: View) : RecyclerView.ViewHolder(view){
fun bindItem(items: Item) {
itemView.name.text = items.name
itemView.desc.text = items.desc
Glide.with(itemView.context).load(items.image).into(itemView.image)
itemView.setOnClickListener {
itemView.context.startActivity(itemView.context.intentFor<DetailsActivity>("image" to bitmap, "name" to items.name, "desc" to items.desc))
}
}
}
SecondActivity
val intent = intent
name = intent.getStringExtra("name")
image = intent.getStringExtra("image")
desc = intent.getStringExtra("desc")
nameTextView.text = name
descTextView.text = desc
Glide.with(this)
.load(image)
.into(imgPhotos)
I have already tried all the code that are provided on this site, but they all didn't work. Thanks!
I am not using Glide but it should be like this.
lateinit imageBitmap : Bitmap
Glide.with(this).asBitmap().load("YOUR_URL").into(object: Target<Bitmap>{
override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>?) {
imageBitmap = resource
}
})
You can send Bitmap directly because it is Parcelable
intent.putExtra("image",imageBitmap)
To getBitmap
val bitmap = intent.extras.getParcelable<Bitmap>("image")
Convert the image to byteArray and pass it through intent. Extract the data through intent on the other side and convert byteArray into bitmap.

Categories

Resources