【问题标题】:How to compress image taken by camera before uploading to firebase?如何在上传到firebase之前压缩相机拍摄的图像?
【发布时间】:2017-10-01 21:03:15
【问题描述】:

我想用相机挑选一张自动压缩或转换成更容易上传的格式的照片。 之后我想自动上传图片。

希望你能帮助我。

这是我的代码:

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

    mStorage = FirebaseStorage.getInstance().getReference();
    mProgressDialog1 = new ProgressDialog(this);
    mCamera = (ImageButton) findViewById(R.id.UpCamera);
    mImageview = (ImageView) findViewById(R.id.imageView1);


    mCamera.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Intent intent1 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            startActivityForResult(intent1, CAMERA_REQUEST_CODE);
        }
    });
}


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



    if (requestCode == CAMERA_REQUEST_CODE && resultCode == RESULT_OK){
        Bitmap photo = (Bitmap) data.getExtras().get("data");
        mImageview.setImageBitmap(photo);
        Toast.makeText(MainActivity.this, "Uploading..", Toast.LENGTH_LONG).show();
        mProgressDialog1.setMessage("Crop Image");
        mProgressDialog1.show();
        Uri uri1 = data.getData();
        StorageReference filepath = mStorage.child("Tries").child(uri1.getLastPathSegment());
        filepath.putFile(uri1).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {

            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                mProgressDialog1.dismiss();
                Uri downloadUri = taskSnapshot.getDownloadUrl();
                Picasso.with(MainActivity.this).load(downloadUri).fit().centerCrop().into(mImageview);
                Toast.makeText(MainActivity.this, "Upload done!", Toast.LENGTH_LONG).show();

            }
        });

    }
}


}

【问题讨论】:

标签: android image upload firebase-storage


【解决方案1】:

然后你需要添加这个方法:

Bitmap bmp = BitmapFactory.decodeFile(miFoto)
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bmp.compress(CompressFormat.JPEG, 70, bos);
InputStream in = new ByteArrayInputStream(bos.toByteArray());
ContentBody foto = new InputStreamBody(in, "image/jpeg", "filename");

点赞:Compress camera image before upload

【讨论】:

  • 位图操作似乎非常笨拙...容易出现内存不足错误(OME)。希望 android 有更好的东西来处理照片。此代码容易出现 OME,如果文件为 40Mb,则将其解码为 Bitmap 会破坏您的 VM。
  • 是的,我已经看到了这个崩溃,你能给我们最好的解决方案吗
  • 我会使用 glide 跳过设置位图然后设置 contentbody 的步骤。看到这个可能会有所帮助,github.com/bumptech/glide/issues/1192
猜你喜欢
  • 1970-01-01
  • 2021-01-03
  • 1970-01-01
  • 2013-10-31
  • 2013-11-04
  • 2018-03-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多