如何在将图像上传到 firebase 存储之前减小图像的大小?

How to reduce the size of image before uploading it to firebase storage?

我已经为图像和视频制作了一个社交应用程序 sharing.However,加载 image.I 需要太多时间,我正在使用滑行 library.Please,请告诉我如何减少从图库中选取的图像大小,图像质量没有显着变化(就像 Instagram 那样),然后将其上传到 firebase storage.Please 求助!

我已经使用 bitmap.compress

将图片上传到 firebase 了
private void postDataToFirebase() {
        mProgressDialog.setMessage("Posting the Blog to Firebase");
        mProgressDialog.setCancelable(false);

        final String titleValue = mPostTitle.getText().toString();
        final String description = mPostDescription.getText().toString();
        if((!TextUtils.isEmpty(titleValue))&& (!TextUtils.isEmpty(description)) && bitmap != null)
        {
            mProgressDialog.show();
            StorageReference filePath = mStorage.child("Blog_Images").child(imagePathName);
            ByteArrayOutputStream bytes = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, 20, bytes);
            String path = MediaStore.Images.Media.insertImage(PostActivity.this.getContentResolver(), bitmap, imagePathName, null);
            Uri uri = Uri.parse(path);
            filePath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                @Override
                public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {

                    Uri downloadUrl = taskSnapshot.getDownloadUrl();

                    DatabaseReference newPost = mDatabaseReference.push();
                    newPost.child("Title").setValue(titleValue);
                    newPost.child("Desc").setValue(description);
                    newPost.child("imageUrl").setValue(downloadUrl.toString());
                    Toast.makeText(PostActivity.this, "Data Posted Successfully to Firebase server", Toast.LENGTH_LONG).show();
                    mProgressDialog.dismiss();
                    Intent intent = new Intent(PostActivity.this, MainActivity.class);
                    startActivity(intent);
                }
            });

        }

    }

bitmap.compress(Bitmap.CompressFormat 格式, int 质量, OutputStream 流)

您可以更改位图的质量并对其进行压缩。

StorageReference childRef2 = [your firebase storage path]
storageRef.child(UserDetails.username+"profilepic.jpg");
                    Bitmap bmp = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    bmp.compress(Bitmap.CompressFormat.JPEG, 25, baos);
                    byte[] data = baos.toByteArray();
                    //uploading the image
                    UploadTask uploadTask2 = childRef2.putBytes(data);
                    uploadTask2.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                        @Override
                        public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                            Toast.makeText(Profilepic.this, "Upload successful", Toast.LENGTH_LONG).show();
                        }
                    }).addOnFailureListener(new OnFailureListener() {
                        @Override
                        public void onFailure(@NonNull Exception e) {
                            Toast.makeText(Profilepic.this, "Upload Failed -> " + e, Toast.LENGTH_LONG).show();
                        }
                    });`

只需继续执行上述步骤,它会减小您的图像大小并将其上传到 firebase 它将图像大小减小到 1 到 2 mb 根据我的经验,4mb 文件变成了 304kb。

filepath 是和 File 所选图像的对象。 :)

我在这里使用此代码在 firebase storeage

上上传压缩图像
@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode==RC_PHOTO_PICKER && resultCode==RESULT_OK)
        {
            mProgressBar.setVisibility(ProgressBar.VISIBLE);
            Uri selectedImageUri = data.getData();

            Bitmap bmp = null;
            try {
                bmp = MediaStore.Images.Media.getBitmap(getContentResolver(), selectedImageUri);
            } catch (IOException e) {
                e.printStackTrace();
            }
            ByteArrayOutputStream baos = new ByteArrayOutputStream();

            //here you can choose quality factor in third parameter(ex. i choosen 25) 
            bmp.compress(Bitmap.CompressFormat.JPEG, 25, baos);
            byte[] fileInBytes = baos.toByteArray();

           StorageReference photoref = chatPhotosStorageReference.child(selectedImageUri.getLastPathSegment());

           //here i am uploading
           photoref.putBytes(fileInBytes).addOnSuccessListener(this, new OnSuccessListener<UploadTask.TaskSnapshot>() {
                       public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                                          // When the image has successfully uploaded, we get its download URL
                           mProgressBar.setVisibility(ProgressBar.INVISIBLE);

                           Uri downloadUrl = taskSnapshot.getDownloadUrl();
                           String id = chatRoomDataBaseReference.push().getKey();
                           String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Calendar.getInstance().getTime());

                           // Set the download URL to the message box, so that the user can send it to the database
                           FriendlyMessageModel friendlyMessage = new FriendlyMessageModel(id,null, userId, downloadUrl.toString(),time);
                   chatRoomDataBaseReference.child(id).setValue(friendlyMessage);
                                       }
                   });
        }
    }

Kotlin 版本

    val userId = FirebaseAuth.getInstance().currentUser!!.uid
    val storageRef = FirebaseStorage.getInstance().getReference("UsersPhotos/${userId}.jpg")

    // compressing image
    val bitmap = MediaStore.Images.Media.getBitmap(contentResolver, imageURI)
    val byteArrayOutputStream = ByteArrayOutputStream()
    bitmap.compress(Bitmap.CompressFormat.JPEG, 25, byteArrayOutputStream)
    val reducedImage: ByteArray = byteArrayOutputStream.toByteArray()

        storageRef.putBytes(reducedImage)
        .addOnSuccessListener {

            Log.i("xxx", "Success uploading Image to Firebase!!!")

            storageRef.downloadUrl.addOnSuccessListener {

                //getting image url
                Log.i("xxx",it.toString())
            
             }.addOnFailureListener {

                        Log.i("xxx", "Error getting image download url")
                    }

        }.addOnFailureListener {

            Log.i("xxx", "Failed uploading image to server")
            
        }