如何在上传到存储之前降低图像质量或分辨率以节省存储空间?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何在上传到存储之前降低图像质量或分辨率以节省存储空间?相关的知识,希望对你有一定的参考价值。

大家好,我正在开发一个社交应用程序,其功能是上传图像

我在这个项目中使用Firebase 但对于一个初学者项目,我使用免费计划为我提供5GB存储空间

所以我想知道如何在上传到存储之前降低图像质量或分辨率以节省存储空间

这是我的代码

UploadpostActivity

 @Override
protected void onActivityResult(int requestCode, int resultCode, Intent 
data) {
    super.onActivityResult(requestCode, resultCode, data);


    if(requestCode == GALLERY_REQUEST && resultCode ==RESULT_OK ){

        mImageURI = data.getData();
        imgSelector.setImageURI(mImageURI);
    }

}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_upload);

    btnUpload=(Button)findViewById(R.id.upload);
    imgSelector =(ImageView) findViewById(R.id.selectImage);
    postDescription = (EditText)findViewById(R.id.descpost);
    postTitle = (EditText)findViewById(R.id.titlepost);
    mProgress= new ProgressDialog(this);


    btnUpload.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            postnow();
        }
    });
    imgSelector.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Intent gallerySelectIntent = new 
    Intent(Intent.ACTION_GET_CONTENT);
            gallerySelectIntent.setType("image/*");
            startActivityForResult(gallerySelectIntent,GALLERY_REQUEST);

        }
    });



 }

private void postnow(){


    mProgress.setMessage("Uploading..");
    mProgress.show();


    String title= postTitle.getText().toString().trim();
    String desc = postDescription.getText().toString().trim();


   StorageReference pathfile = FirebaseStorage.getInstance()
           .getReference("UsersImages")
           .child(mImageURI.getLastPathSegment());


    pathfile.putFile(mImageURI)
            .addOnSuccessListener(new 
    OnSuccessListener<UploadTask.TaskSnapshot>() {
                @Override
                public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) 
    {
                    // Get a URL to the uploaded content
                    Uri downloadUrl = taskSnapshot.getDownloadUrl();

                    mProgress.dismiss();
                    Toast.makeText(UploadActivity.this,"Upload 
          Successfully",Toast.LENGTH_LONG).show();
                }
            })
            .addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception exception) {
                    // Handle unsuccessful uploads
                    // ...

                    Toast.makeText(UploadActivity.this,"Something Went Wrong 
       , Error",Toast.LENGTH_LONG).show();
                }
            });

  }
  }

我感谢你的时间

答案

通过此方法减小位图的大小并将其上传到服务器..

public static Bitmap resizeBitmapKeepAspectRatio(Bitmap originalImage, int width, int height) {
        Bitmap background = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);

        float originalWidth = originalImage.getWidth();
        float originalHeight = originalImage.getHeight();

        Canvas canvas = new Canvas(background);

        float scale = width / originalWidth;

        float xTranslation = 0.0f;
        float yTranslation = (height - originalHeight * scale) / 2.0f;

        Matrix transformation = new Matrix();
        transformation.postTranslate(xTranslation, yTranslation);
        transformation.preScale(scale, scale);

        Paint paint = new Paint();
        paint.setFilterBitmap(true);

        canvas.drawBitmap(originalImage, transformation, paint);

        return cropBitmapTransparency(background);
    }


public static Bitmap cropBitmapTransparency(Bitmap sourceBitmap) {
        int minX = sourceBitmap.getWidth();
        int minY = sourceBitmap.getHeight();
        int maxX = -1;
        int maxY = -1;
        for (int y = 0; y < sourceBitmap.getHeight(); y++) {
            for (int x = 0; x < sourceBitmap.getWidth(); x++) {
                int alpha = (sourceBitmap.getPixel(x, y) >> 24) & 255;
                if (alpha > 0)   // pixel is not 100% transparent
                {
                    if (x < minX)
                        minX = x;
                    if (x > maxX)
                        maxX = x;
                    if (y < minY)
                        minY = y;
                    if (y > maxY)
                        maxY = y;
                }
            }
        }
        if ((maxX < minX) || (maxY < minY))
            return null; // Bitmap is entirely transparent

        // crop bitmap to non-transparent area and return:
        return Bitmap.createBitmap(sourceBitmap, minX, minY, (maxX - minX) + 1, (maxY - minY) + 1);
    }

以上是关于如何在上传到存储之前降低图像质量或分辨率以节省存储空间?的主要内容,如果未能解决你的问题,请参考以下文章

如何在将图像上传到 Firebase 之前调整其大小?

上传图片:在不损失质量的情况下降低分辨率(Swift)

如何在上传到服务器之前减小图像文件大小

MediaStore.Images.Media 降低存储到画廊的图像质量

有没有办法降低 iPad 照片质量

现在上传的照片为啥压缩那么厉害