我之前的实现方式是将JPEG格式的图片上传到Firebase存储中,并且没有进行任何压缩。
private fun sendToFirebase() {
if (imgUri != null) {
val fileRef = storageRef!!.child(username+ ".jpg")
....
// code to upload and read image url
}
}
决定编写一个图像压缩技术,用于压缩图像并上传到 Firebase 存储
结果:实现了图像压缩技术,请见下文
新增代码以压缩图像
URI to Bitmap
val bitmap = MediaStore.Images.Media.getBitmap(activity?.contentResolver, imgUri)
Method to compress Bitmap
private fun compressBitmap(bitmap: Bitmap, quality:Int):Bitmap{ val stream = ByteArrayOutputStream() bitmap.compress(Bitmap.CompressFormat.WEBP, quality, stream) val byteArray = stream.toByteArray() return BitmapFactory.decodeByteArray(byteArray, 0, byteArray.size) }
Bitmap compression Implementation
compressBitmap(bitmap, 80)
问题:如何将同一压缩图像上传到Firebase存储
private fun sendToFirebase() {
if (imgUri != null) {
// code to convert uri to bitmap <start>
val bitmap = MediaStore.Images.Media.getBitmap(activity?.contentResolver, imgUri)
compressBitmap(bitmap, 80)
// code to convert uri to bitmap <end>
// old implementation
.....
}
}