简体   繁体   中英

Reduce image size before uploading to firebase storage

I know there are many posts similar to this one, trust me I've tried lots of them, but it seems that for some reason this is not working for me. I want to upload a smaller size image to my firebase storage, this is my current code:

public fun uploadPictureToFirebaseStorage(context: Context, bitmap: Bitmap?,uri: Uri?,type :uploadType ) {
    val storage: FirebaseStorage = FirebaseStorage.getInstance()
    val storageRef: StorageReference = storage.getReference()
    val imgName = generateNewFileName()
    var riversRef : StorageReference? = null
    if(type == uploadType.POST) {
        riversRef =
                storageRef.child("images/posts/" + getUserName(context) + "/" + imgName)
    }
    else
    {
        riversRef =  storageRef.child("images/profiles/" + getUserName(context) )

    }
    var uploadTask : UploadTask? = null
    if (bitmap != null) {
        uploadTask = uploadFromBitmap(bitmap, riversRef)
    }
    else if(uri != null)
    {
        uploadTask = uploadFromUri(uri,riversRef,type)
    }
    uploadTask?.addOnFailureListener(OnFailureListener {
        Toast.makeText(context,"The image wasn't uploaded. Try again later!",Toast.LENGTH_LONG).show()
    })?.addOnSuccessListener(OnSuccessListener<Any?> {
        Toast.makeText(context,"The image was uploaded",Toast.LENGTH_LONG).show()
        if(type == uploadType.POST)
        {
            uploadPictureNameToDB(context,imgName)
            updateFriendFeed(getUserName(context)!!,imgName)
        }
    })
}

and the uploadFromBitmap function that's used in that is:

private fun uploadFromBitmap(bitmap: Bitmap, storageRef:StorageReference): UploadTask {
    val baos = ByteArrayOutputStream()
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos)
    val data: ByteArray = baos.toByteArray()
    return storageRef.putBytes(data)
}

Now, as many of the posts suggested, I have tried rescaling the image (using scale method), tried changing its extension to PNG and tried changing the quality from 100 to lower (like 20), however nothing worked. I will mention that the picture I tried these things on has the size of 248KB, and everything I changed kept upload it with that size.
Is it possible that the resizing doesn't work on pictures lower than specific size?

Or if not, why is this not working I don't understand, is there something wrong with my code?

Okay I have solved the problem, all the methods were right, I just wasn't paying attention to the fact that the first function was entering through Uri and not through Bitmap (in the if else statement, the bitmap was null and the uri wasn't).

So all I had to do was implying the changes to the uploadFromUri() function

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM