【发布时间】:2021-01-04 05:40:56
【问题描述】:
在我的 Android 应用中,我允许用户从他们的图库中选择一张图片作为他们的个人资料图片。
这是从他们的图库中选择图片的代码:
profile_image_view.setOnClickListener {
val intent = Intent(Intent.ACTION_PICK)
intent.type = "image/*"
startActivityForResult(intent, PROFILE_REQUEST_CODE)
}
这是我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)
}
}
这是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()
}
}
如何提醒用户他们选择的图片太大?在调用uploadProfileImage 之前如何确定图像的大小?或者 Firebase 存储中是否有办法防止上传尺寸过大的图像?我希望最大照片大小为 2 MB。
【问题讨论】:
-
profileBitmap.getWith() 和 profileBitmap.getHeight()。
标签: android firebase-storage android-bitmap android-image android-gallery