如何在上传图片到Firebase存储之前减小图片的大小?

14

我制作了一个图片和视频分享的社交应用,但是它加载图片需要太长时间。我正在使用Glide库,请告诉我如何在不影响图片质量的情况下减小从图库中选取的图片大小(就像Instagram做的那样),然后将其上传到Firebase存储。请帮帮我!


请在此处发布您的代码 - Quick learner
1
这听起来像是一个以前必须解决过的问题。你尝试过什么吗?这些看起来很有希望:http://stackoverflow.com/search?q=%5Bandroid%5D+How+to+reduce+the+size+of+image - Frank van Puffelen
2
Instagram(以及许多其他社交媒体应用程序)会将图像转码为较低的分辨率和/或不同的格式(如webp),以便尽快提供适当质量的图像。 IG还会立即获得极低质量的照片,并在加载屏幕上模糊它,这是一个不错的效果。您可以使用诸如imgix或cloudinary之类的工具来获取即时调整大小、压缩照片,或者使用GAE Images API(https://cloud.google.com/appengine/docs/python/images/)构建自己的工具。 - Mike McDonald
当我从JavaScript上传时,我该如何做到这一点? - user663031
4个回答

42
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,就像我的经验一样,4 MB的文件变成了304 KB。

filepath是你选择的图像的File对象。 :)


1
非常感谢,这对我非常有效...为什么没有点赞这个答案......+10 - demo
它像魔法一样奏效,谢谢!但是图片倾斜了。我该怎么修复? - Ahsan
谢谢,它完美地工作了。将大小为5.98 MB的图像缩小到990 KB。 - Kartik Agarwal
1
上传到 Firebase 会将图像旋转。 - hitesh
谢谢!!!我一直在寻找,但是其他的似乎都不起作用,直到我尝试了你的。 - Team chang

4

我在这里使用以下代码上传压缩图像到 firebase storage

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

它起作用了,将图像从1.32 MB压缩到了323 KB。 - MoonLight

0

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

0

我已经使用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 format,int quality,OutputStream stream)

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


你的图片路径名是什么? - Shubh.J

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接