从相机捕获图像并上传到Firebase

时间:2016-12-29 09:03:45

标签: android firebase android-camera firebase-storage

我正在开发一个简单的博客应用,允许用户将照片从电话库和说明上传到Firebase服务器。我正在尝试修改我当前的项目,以允许用户从相机捕获照片并将其上传到firebase服务器。

目前,我能够将我捕获的图像显示在图像按钮中,但是我无法将我的图像发布到firebase服务器(“提交帖子”按钮不会对我的onclick功能做出反应)。

我怀疑我的startPosting()函数中有一些错误,或者我没有正确编码图像?请帮忙。

package simpleblog2.emily.example.com.simpleblog2;

import android.app.ProgressDialog;
import android.content.ContentProvider;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.Image;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;

import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import com.squareup.picasso.Picasso;

import com.theartofdev.edmodo.cropper.CropImage;

import java.io.File;


public class PostActivity extends AppCompatActivity {

    private ImageButton mSelectImage;
    private EditText mPostTitle;
    private EditText mPostDesc;
    private Button mSubmitBtn;
    private ProgressDialog mProgress;
    private DatabaseReference mDatabase;

    private Uri mImageUri = null;

    private static final int GALLERY_REQUEST = 1;

    private static final int CAMERA_REQUEST_CODE = 1;

    private StorageReference mStorage;

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

        mStorage = FirebaseStorage.getInstance().getReference();
        mDatabase = FirebaseDatabase.getInstance().getReference().child("Blog");

        mSelectImage = (ImageButton) findViewById(R.id.imageSelect);
        mPostTitle = (EditText) findViewById(R.id.titleField);
        mPostDesc = (EditText) findViewById(R.id.descField);
        mSubmitBtn = (Button) findViewById(R.id.submitBtn);

        mProgress = new ProgressDialog(this);

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

                Intent intent1 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                startActivityForResult(intent1, CAMERA_REQUEST_CODE);
                intent1.setType("image/*");

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

        mSubmitBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startPosting();
            }
        });
    }

    private void startPosting() {

        mProgress.setMessage("Posting to blog...");


        final String title_val = mPostTitle.getText().toString().trim();
        final String desc_val = mPostDesc.getText().toString().trim();
        if (!TextUtils.isEmpty(title_val) && !TextUtils.isEmpty(desc_val) && mImageUri != null) {

            mProgress.show();
            StorageReference filepath = mStorage.child("Blog_Images").child(mImageUri.getLastPathSegment());

            filepath.putFile(mImageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                @Override
                public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                    Uri downloadUrl = taskSnapshot.getDownloadUrl();

                    DatabaseReference newPost = mDatabase.push();
                    newPost.child("title").setValue(title_val);
                    newPost.child("desc").setValue(desc_val);
                    newPost.child("image").setValue(downloadUrl.toString());


                    mProgress.dismiss();
                    startActivity(new Intent(PostActivity.this, MainActivity.class));
                }
            });
        }
    }

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




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

      /*   mImageUri = data.getData();
            mSelectImage.setImageURI(mImageUri);

            CropImage.activity(mImageUri)
                    .setGuidelines(CropImageView.Guidelines.ON)

                    .start(this);

*/

            Bitmap mImageUri = (Bitmap) data.getExtras().get("data");
            mSelectImage.setImageBitmap(mImageUri);
       }


        if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
            CropImage.ActivityResult result = CropImage.getActivityResult(data);
            if (resultCode == RESULT_OK) {
                Uri resultUri = result.getUri();
                mSelectImage.setImageURI(resultUri);
            } else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
                Exception error = result.getError();
            }
        }


    }



}

4 个答案:

答案 0 :(得分:4)

我找到了一个问题的解决方案,我意识到我可以使用data.getData()函数获取捕获的数据,而不是使用Bitmap函数:

 mImageUri = data.getData();
            mSelectImage.setImageURI(mImageUri);

此外,以前我没有意识到我的作物&#39;功能无法正常工作,因为我缺少:

mImageUri = resultUri;

我意识到有一个问题,如果我没有裁剪我的捕获图像,火基无法处理高分辨率(或存储大小?它将加载非常慢/图像没有出现),这可以通过“裁剪”解决问题。功能。

最终代码如下: 感谢大家的帮助。

package simpleblog2.emily.example.com.simpleblog2;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.media.Image;
import android.net.Uri;

import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;


import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;

import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;


import com.theartofdev.edmodo.cropper.CropImage;
import com.theartofdev.edmodo.cropper.CropImageView;


public class PostActivity extends AppCompatActivity {

    private ImageButton mSelectImage;
    private EditText mPostTitle;
    private EditText mPostDesc;
    private Button mSubmitBtn;
    private ProgressDialog mProgress;
    private DatabaseReference mDatabase;

    private Uri mImageUri = null;

    private static final  int GALLERY_REQUEST =1;

    private static final int CAMERA_REQUEST_CODE=1;

    private StorageReference mStorage;

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

        mStorage = FirebaseStorage.getInstance().getReference();
        mDatabase = FirebaseDatabase.getInstance().getReference().child("Blog");

        mSelectImage = (ImageButton) findViewById(R.id.imageSelect);
        mPostTitle = (EditText)  findViewById(R.id.titleField);
        mPostDesc = (EditText) findViewById(R.id.descField);
        mSubmitBtn = (Button) findViewById(R.id.submitBtn);

        mProgress = new ProgressDialog(this);

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

                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

                if (intent.resolveActivity(getPackageManager()) != null) {
                    startActivityForResult(intent, CAMERA_REQUEST_CODE);
                }
                //startActivityForResult(intent,CAMERA_REQUEST_CODE);


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

                */

            }
        });

        mSubmitBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startPosting();
            }
        });
    }



    private void startPosting(){

        mProgress.setMessage("Posting to blog...");


        final String title_val = mPostTitle.getText().toString().trim();
        final String desc_val = mPostDesc.getText().toString().trim();
        if(!TextUtils.isEmpty(title_val)&&!TextUtils.isEmpty(desc_val) && mImageUri != null){

            mProgress.show();
            StorageReference filepath = mStorage.child("Blog_Images").child(mImageUri.getLastPathSegment());

            filepath.putFile(mImageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                @Override
                public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                    Uri downloadUrl =taskSnapshot.getDownloadUrl();

                    DatabaseReference newPost = mDatabase.push();
                    newPost.child("title").setValue(title_val);
                    newPost.child("desc").setValue(desc_val);
                    newPost.child("image").setValue(downloadUrl.toString());


                    mProgress.dismiss();
                    startActivity(new Intent(PostActivity.this,MainActivity.class));
                }
            });
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
      // if(requestCode == GALLERY_REQUEST && resultCode == RESULT_OK){
       if(requestCode == CAMERA_REQUEST_CODE && resultCode == RESULT_OK){




        mImageUri = data.getData();
            mSelectImage.setImageURI(mImageUri);

            CropImage.activity(mImageUri)
                    .setGuidelines(CropImageView.Guidelines.ON)
                    .setAspectRatio(1,1)
                    .start(this);




        /* Bitmap mImageUri1 = (Bitmap) data.getExtras().get("data");
         mSelectImage.setImageBitmap(mImageUri1);

          Toast.makeText(this, "Image saved to:\n" +
                  data.getExtras().get("data"), Toast.LENGTH_LONG).show();


*/



        }

        if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
            CropImage.ActivityResult result = CropImage.getActivityResult(data);
            if (resultCode == RESULT_OK) {
                Uri resultUri = result.getUri();

                mSelectImage.setImageURI(resultUri);
                mImageUri = resultUri;

            } else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
                Exception error = result.getError();
            }
        }


    }




}

答案 1 :(得分:0)

如果auth!= null之前,我将其更改为true,所以if将始终评估为true。

  private void uploadFile() {
    //if there is a file to upload
    if (filePath != null) {
        //displaying a progress dialog while upload is going on
        final ProgressDialog progressDialog = new ProgressDialog(this);
        progressDialog.setTitle("Uploading");
        progressDialog.show();

        StorageReference riversRef = storageReference.child("Blog_Images.jpg");
        riversRef.putFile(filePath)
                .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                    @Override
                    public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                        //if the upload is successfull
                        //and displaying a success toast
                        Toast.makeText(getApplicationContext(), "File Uploaded ", Toast.LENGTH_LONG).show();
                    }
                })
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception exception) {
                        //if the upload is not successfull
                        //hiding the progress dialog
                        progressDialog.dismiss();

                        //and displaying error message
                        Toast.makeText(getApplicationContext(), exception.getMessage(), Toast.LENGTH_LONG).show();
                    }
                })
                .addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
                    @Override
                    public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
                        //calculating progress percentage
                        double progress = (100.0 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount();

                        //displaying percentage in progress dialog
                        progressDialog.setMessage("Uploaded " + ((int) progress) + "%...");
                    }
                });
    }
    //if there is not any file
    else {
        //you can display an error toast
    }
}

答案 2 :(得分:0)

您的班级字段mImageUri永远不会被初始化。您将接收到的位图放在本地字段中,称为与类字段相同。

Bitmap mImageUri = (Bitmap) data.getExtras().get("data");
mSelectImage.setImageBitmap(mImageUri);

因此,情况永远不会成真。

if (!TextUtils.isEmpty(title_val) && !TextUtils.isEmpty(desc_val) && mImageUri != null) 

答案 3 :(得分:0)

&#13;
&#13;
   if (requestCode == CAMERA_REQUEST_CODE && resultCode == RESULT_OK) {

      /*   mImageUri = data.getData();
            mSelectImage.setImageURI(mImageUri);

            CropImage.activity(mImageUri)
                    .setGuidelines(CropImageView.Guidelines.ON)

                    .start(this);

*/

            Bitmap mImageUri = (Bitmap) data.getExtras().get("data");
            mSelectImage.setImageBitmap(mImageUri);
       }
&#13;
&#13;
&#13;

您的URI有可能null。我想,这就是问题所在。 除非你在其他地方做到这一点?

可能会加载图片,因为requestCode = CAMERA_REQUEST_CODE但不是CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE

我将在下面发布我曾经做过的代码,但是你需要先了解一些事情。 从Android版本7使用Uri.parseFromFile(文件)返回错误,因为谷歌想限制您的访问权限。从现在开始,如果你想获得文件uri,你应该使用FileProvider

  1. 在清单中声明permmisions和FileProvider:
  2. &#13;
    &#13;
           
    //File provider declaration in manifest.
            <provider
                android:name="android.support.v4.content.FileProvider"
                android:authorities="com.hadas.yotam.manchworkers.provider"
                android:exported="false"
                android:grantUriPermissions="true">
                <meta-data
                    android:name="android.support.FILE_PROVIDER_PATHS"
                    android:resource="@xml/provider_paths"/>
            </provider>
    &#13;
    &#13;
    &#13;

    &#13;
    &#13;
    //in new xml file define the location you need permmision to, the code below give you permmision for any external file.
    <paths xmlns:android="http://schemas.android.com/apk/res/android">
        <external-path name="external_files" path="."/>
    </paths>
    &#13;
    &#13;
    &#13;

    所以现在上传时使用全局Uri变量如果onActivityResault成功,则代码如下:

    &#13;
    &#13;
    if(Build.VERSION.SDK_INT>=24) {
                                String file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)+"/" + Calendar.getInstance().getTimeInMillis() + ".jpg";
                                File file1 = new File(file);
                                photoURI = FileProvider.getUriForFile(this, getApplicationContext().getPackageName() + ".provider", file1);
                                intent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
                            }
    &#13;
    &#13;
    &#13;

    然后在你的onActivityResult中你检查你的photoURI是否为null,如果它是真的(它为null) 使用photoURI = data.getData();

    &#13;
    &#13;
    //if phone android version greater or equal to Marshmelo                    
    
    if(Build.VERSION.SDK_INT>Build.VERSION_CODES.M){
    
    //check if have permmission to write to external + permmision to camera
    
                        if(ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE)== PackageManager.PERMISSION_GRANTED &&
                                ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.CAMERA)== PackageManager.PERMISSION_GRANTED){
    
    //if its have permission then new intent to capture image
    
                            intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    
    //if android version >= 24 (Android Nugget)
    
                            if(Build.VERSION.SDK_INT>=24) {
    
    //create new String to pictures directory and set the file name to current_time.jpg
                                String file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)+"/" + Calendar.getInstance().getTimeInMillis() + ".jpg";
                                File file1 = new File(file);
    
    //set GLOBAL variable Uri from the file using FileProvider
    
                                photoURI = FileProvider.getUriForFile(this, getApplicationContext().getPackageName() + ".provider", file1);
    
    //add the file location the intent (the picture will be save to this file)
    
                                intent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
                            }
                                tagIntent = CAPTURE_RESAULT;
    //else - dont have permission, request for permission
                        }else{
                            requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.CAMERA},CAPTURE_RESAULT);
                        }
    else - 
                    }else{
    // same thing only without FileProvider (FileProvider only required since Nugget)
    
                            intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                            String file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)+"/" + Calendar.getInstance().getTimeInMillis() + ".jpg";
                            File file1 = new File(file);
                            photoURI = Uri.fromFile(file1);
                            intent.putExtra(MediaStore.EXTRA_OUTPUT,photoURI);
                        tagIntent = CAPTURE_RESAULT;
                    }
    
    //if phone can handle the intent, start the intent for resault.
    
                    if(intent.resolveActivity(getPackageManager())!=null) {
                startActivityForResult(intent,tagIntent);
                    }
    &#13;
    &#13;
    &#13;