簡體   English   中英

在上傳到 firebase 存儲之前減小圖像大小

[英]Reduce image size before uploading to firebase storage

我知道有很多類似的帖子,相信我,我已經嘗試了很多,但似乎由於某種原因這對我不起作用。 我想將較小尺寸的圖像上傳到我的 firebase 存儲,這是我當前的代碼:

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)
        }
    })
}

以及其中使用的uploadFromBitmap function 是:

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)
}

現在,正如許多帖子所建議的那樣,我嘗試重新縮放圖像(使用縮放方法),嘗試將其擴展名更改為 PNG,並嘗試將質量從 100 更改為更低(如 20),但沒有任何效果。 我會提到我嘗試這些東西的圖片大小為 248KB,我更改的所有內容都以該大小上傳。
調整大小是否可能不適用於低於特定尺寸的圖片?

或者如果沒有,為什么這不起作用我不明白,我的代碼有問題嗎?

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)。

所以我所要做的就是暗示對uploadFromUri() function 的更改

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM