I found so many questions on the topic but none had a full working example.
My case is simple:
- get picked image
- compress image
- upload compressed image to Firebase Storage
My current code (without compression):
Fragment:
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
when (requestCode) {
RC_PICK_IMAGE ->
if (resultCode == Activity.RESULT_OK)
data?.data?.let { viewModel.updateUserPicture(it) }
}
}
ViewModel:
fun updatePhotoUrl(photoUrl: Uri?): Task<Void> =
Storage.uploadFile("/$PS_USERS/$uid", photoUrl)
.continueWithTask { ... }
Storage: (object to wrap Firebase interactions)
fun uploadFile(path: String, uri: Uri): Task<Uri> {
val imageRef = storageRef.child(path)
val uploadTask = imageRef.putFile(uri)
// Return the task getting the download URL
return uploadTask.continueWithTask { task ->
if (!task.isSuccessful) {
task.exception?.let {
throw it
}
}
imageRef.downloadUrl
}
}
This works perfectly.
Now my question is: what is the right way to add compression in this process?
- I found many answers pointing to the Compressor library (like here & here) and tried it, but it doesn't work with gallery result uris. I found ways to get the actual uri from that (like here), but they feel like a lot of boilerplate code, so it doesn't feel like the best practice.
- I also found many answers using
bitmap.compress
(like here & here) and tried it too, but it asks for a bitmap. Getting the bitmap is easy withMediaStore.Images.Media.getBitmap
, but it is deprecated, and this solution made me doubt if it's the right direction. Also, holding the bitmap in my LiveData object (to show on screen until the actual save, in the edit screen), instead of a uri, feels weird (I use Glide for presenting the images).
On top of that, both solutions demand a context. I think compression is a process that should belong in the backend (or Repository class. The Storage object in my case), So they feel a bit off.
Can someone please share a full working example of this trivial use case?