In my Android app, I allow the user to select a picture from their gallery for their profile picture.
This is the code for selecting an image from their gallery:
profile_image_view.setOnClickListener {
val intent = Intent(Intent.ACTION_PICK)
intent.type = "image/*"
startActivityForResult(intent, PROFILE_REQUEST_CODE)
}
This is the code for my onActivityResult
:
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
// Result of our profile image change
if (requestCode == PROFILE_REQUEST_CODE && resultCode == Activity.RESULT_OK && data != null) {
// Proceed and check what the selected image was
profileImageUri = data.data!!
// Get the bitmap of the image
if (Build.VERSION.SDK_INT < 28) {
profileBitmap =
MediaStore.Images.Media.getBitmap(contentResolver, profileImageUri)
} else {
val source =
ImageDecoder.createSource(contentResolver, profileImageUri)
profileBitmap = ImageDecoder.decodeBitmap(source)
}
// Upload the user's profile image to Firebase Storage
uploadProfileImage(profileBitmap)
}
}
This is the code for uploadProfileImage
:
private fun uploadProfileImage(bitmap: Bitmap) {
loadingDialog.startLoadingDialog()
val filename: String = auth.currentUser!!.uid
val ref: StorageReference = storage.getReference("/images/$filename")
ref.putFile(profileImageUri)
.addOnSuccessListener {
ref.downloadUrl.addOnSuccessListener {
userInfo.child("profileImageUrl").setValue(it.toString())
profile_image_view.setImageBitmap(bitmap)
loadingDialog.dismissDialog()
}
}
.addOnFailureListener {
loadingDialog.dismissDialog()
Toast.makeText(
applicationContext, "${it.message}",
Toast.LENGTH_LONG
).show()
}
}
How do I alert the user that the image they have picked is too big? How do I figure out the size of the image before calling uploadProfileImage
? Or is there a way in Firebase Storage to prevent images from being uploaded where the size is too big? I want the maximum photo size to be 2 MB.