2017-05-03 58 views
0

我想用自动压缩的照相机拍摄照片或转换成更容易上传的格式。 之后,我想自动上传图像。如何在上传到Firebase之前压缩相机拍摄的图像?

希望你能帮助我。

这是我的代码:

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

      } 
     }); 

    } 
} 


} 
+0

看[这里](https://firebase.google .com/docs/storage/android/upload-files)在Firebase参考中有一个如何上传位图的例子。在这个例子中有一个Bitmap.compress调用,您可以在其中指定压缩质量。 –

+0

将您的文件上传到64base之前上传它: [http://stackoverflow.com/questions/36189503/take-picture-and-convert-to-base64](http://stackoverflow.com/questions/36189503/拍照和转换为base64) –

+0

@IbrahimHaouari base64编码将使数据*更大*,不像Jessef所要求的那样小。 –

回答

0

您需要添加此梅索德则:

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

+0

位图操作似乎非常沉重......易于发生内存异常(OME)。希望android能够更好地处理照片。这个代码容易出现OME,如果文件是40Mb将它解码为Bitmap将会影响你的虚拟机。 – JPM

+0

是的这是真的我见过这个崩溃,你能给我们最好的解决方案请 –

+0

我会用滑翔跳过设置位图,然后设置contentbody的步骤。看到这可能会有所帮助,https://github.com/bumptech/glide/issues/1192 – JPM

相关问题