【问题标题】:How Can I Compress Images Before Uploading to Firebase?如何在上传到 Firebase 之前压缩图像?
【发布时间】:2020-06-29 10:28:17
【问题描述】:

我正在创建一个社交网络应用程序,用户可以在其中发布图像,因此当用户上传其图像时,它的尺寸非常大,而当我检索该图像时,使用 Picasso 会花费太多时间。 有没有办法在上传之前压缩这些图像而不会造成明显的质量损失,以便可以非常有效和快速地检索它们。 P.S:我使用 Firebase 作为后端服务器。

这是我上传图片的代码。

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {

    if(requestCode == Gallery_Pick && resultCode == RESULT_OK && data != null){
        ImageUri = data.getData();
        SelectPostImage.setImageURI(ImageUri);
    }
    super.onActivityResult(requestCode, resultCode, data);
}

final StorageReference filePath = PostImagesRef.child("Post Images").child(ImageUri.getLastPathSegment() + postRandomName + ".jpg");

    final UploadTask uploadTask = filePath.putFile(ImageUri);

    uploadTask.addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception e) {
            String message = e.toString();
            Toast.makeText(PostActivity.this, "Some Error Occured"+message, Toast.LENGTH_SHORT).show();
            loadingBar.dismiss();
        }
    }).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
        @Override
        public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
            Toast.makeText(PostActivity.this, "Image Uploaded Successfully", Toast.LENGTH_SHORT).show();
            Task<Uri> urlTask = uploadTask.continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
                @Override
                public Task<Uri> then(@NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
                    if(!task.isSuccessful()){
                        throw task.getException();
                    }
                    downloadImageUrl = filePath.getDownloadUrl().toString();

                    return filePath.getDownloadUrl();
                }
            }).addOnCompleteListener(new OnCompleteListener<Uri>() {
                @Override
                public void onComplete(@NonNull Task<Uri> task) {
                    if(task.isSuccessful()){

                        downloadImageUrl = task.getResult().toString();
                        Toast.makeText(PostActivity.this, "Saved To Database Successfully", Toast.LENGTH_SHORT).show();
                        SavingPostInformationToDatabase();

                    }
                }
            });
        }
    });

请帮助我。任何帮助或建议都将是可观的。 提前致谢。!! :)

【问题讨论】:

    标签: android image firebase compression


    【解决方案1】:

    您可以简单地使用 Glide 调整图片大小并使用该图片上传到 firebase

    Glide.with(requireActivity())
                    .asBitmap()
                    .override(YOUR_IMAGE_SIZE, YOUR_IMAGE_SIZE)
                    .load(uri)
                    .into(object : CustomTarget<Bitmap>() {
                        override fun onResourceReady(
                            resource: Bitmap,
                            transition: Transition<in Bitmap>?
                        ) {
    
                            // using bitmapToByte(resource) -> byte
                            // using filePath.putBytes(data) -> uploadTask
                             val filePath = PostImagesRef.child("Post Images").child(ImageUri.getLastPathSegment() + postRandomName + ".jpg")
    
                             val uploadTask = filePath.putBytes(bitmapToByte(resource))
                        }
    
                        override fun onLoadCleared(placeholder: Drawable?) {
                            // this is called when imageView is cleared on lifecycle call or for
                            // some other reason.
                            // if you are referencing the bitmap somewhere else too other than this imageView
                            // clear it here as you can no longer have the bitmap
                        }
                    })
    

    bitmapToByte函数

     fun bitmapToByte(bitmap: Bitmap): ByteArray {
        val stream = ByteArrayOutputStream()
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream)
        return stream.toByteArray()
    }
    

    希望对你有帮助

    【讨论】:

      【解决方案2】:

      你可以试试这个方法。更改此 onActivityResult

      if(requestCode == Gallery_Pick && resultCode == RESULT_OK && data != null) {
                  try {
                      Uri imageUri = imageReturnedIntent.getData();
                      InputStream imageStream = getContentResolver().openInputStream(imageUri);
                      Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);
      
                      selectedImage = getResizedBitmap(selectedImage, 400,300);// 400 and 300 height and width, replace with desired size
      
                      imageView.setImageBitmap(selectedImage); // your desired image
      
      
                  } catch (FileNotFoundException e) {
                      e.printStackTrace();
                  }
      

      这是您需要的 getResizedBitmap 方法。

          public Bitmap getResizedBitmap(Bitmap bm, int newHeight, int newWidth) {
          int width = bm.getWidth();
          int height = bm.getHeight();
          float scaleWidth = ((float) newWidth) / width;
          float scaleHeight = ((float) newHeight) / height;
      
          // create a matrix for the manipulation
          Matrix matrix = new Matrix();
      
          // resize the bit map
          matrix.postScale(scaleWidth, scaleHeight);
      
          // recreate the new Bitmap
          Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, false);
      
          return resizedBitmap;
      }
      

      【讨论】:

      • 它肯定会压缩大小,但不会压缩那么多。它将 9mb 图像大小转换为最大 6 MB。我想要它在 kb 中,以便它加载超级快。有什么建议吗?顺便说一句,感谢您的帮助。
      • 你是说selectedImage = getResizedBitmap(selectedImage, 400,300);// 400 and 300 height and width, replace with desired size 会提供一个 6MB 的文件吗?我们不相信你。
      • 是的,我上传了一个 7.15 MB 的文件,它刚刚转换为 6.82 MB。就这么多,它正在压缩图像。您还有其他建议可以进一步压缩无损质量吗?
      • @AnkurSinghal 也许这个答案应该对你有更多帮助stackoverflow.com/a/823966/8332511
      猜你喜欢
      • 2021-01-03
      • 2017-10-01
      • 2018-10-06
      • 1970-01-01
      • 2023-03-19
      • 2019-02-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多