简体   繁体   中英

How to capture image from camera and upload to Firebase

I am trying to take a photo with the camera and upload it to Firebase. I'm using a AlertDialog to ask the user if they want to use the camera or select image from gallery. I can take a picture with the camera but when I try to upload the image it says no image found.

Here is my image selection method:

    private void imageSelect(Context context) {
    final CharSequence[] options = { "Take Photo", "Choose from Gallery","Cancel" };

    AlertDialog.Builder builder = new AlertDialog.Builder(context);
    builder.setTitle("Choose Image");

    builder.setItems(options, new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int item) {

            if (options[item].equals("Take Photo")) {
                Intent takePicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                startActivityForResult(takePicture, 0);

            } else if (options[item].equals("Choose from Gallery")) {
                Intent pickPhoto = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(pickPhoto , 1);

            } else if (options[item].equals("Cancel")) {
                dialog.dismiss();
            }
        }
    });
    builder.show();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    switch(requestCode) {
        case 0:
            if(resultCode == RESULT_OK){
                filePath = data.getData();
            }

            break;
        case 1:
            if(resultCode == RESULT_OK){
                filePath = data.getData();
                try {
                    Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
            }
            break;
    }
}

Here is my upload image method:

    private void uploadImage() {
    if (filePath != null) {
        //Code for showing progressDialog while uploading
        ProgressDialog progressDialog = new ProgressDialog(this);
        progressDialog.setTitle("Uploading...");
        progressDialog.show();

        StorageReference ref = storageReference.child("images/" + name);
        //Adding listeners on upload or failure of image
        ref.putFile(filePath).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                //Image uploaded successfully
                progressDialog.dismiss();
                Toast.makeText(add_property.this, "Image Uploaded!", Toast.LENGTH_SHORT).show();
            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                //Error, Image not uploaded
                progressDialog.dismiss();
                Toast.makeText(add_property.this, "Failed " + e.getMessage(), Toast.LENGTH_SHORT).show();
            }
        }).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
            //Progress Listener for loading
            @Override
            public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
                double progress = (100.0 * taskSnapshot.getBytesTransferred() / taskSnapshot.getTotalByteCount());
                progressDialog.setMessage("Uploaded " + (int) progress + "%");
            }
        });
    }
    else {
        Toast.makeText(getApplicationContext(),"No image found",Toast.LENGTH_SHORT).show();
    }
}

Thanks in advance for any help friends.

This is my code which I used for my app and worked fine, try it if it works then congrats

 public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_upload, container, false);
        requireActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        Button chooseImageButton = view.findViewById(R.id.upload_image_button);
        Button uploadImageButton = view.findViewById(R.id.done_button);
        uploadImageView = view.findViewById(R.id.upload_image_view);
        storageReference = FirebaseStorage.getInstance().getReference("uploads");
        databaseReference = FirebaseDatabase.getInstance().getReference("uploads");
        chooseImageButton.setOnClickListener(v -> openFileChooser());
        uploadImageButton.setOnClickListener(v -> {
            if (mUploadTask != null && mUploadTask.isInProgress()) {
                Toast.makeText(getActivity(), "Upload in Progress", Toast.LENGTH_SHORT).show();

            } else {
                uploadToFirebase(mImageUri);
            }


        });

        return view;
    }


    private void openFileChooser() {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(intent, PICK_IMAGE_REQUEST);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK
                && data != null && data.getData() != null) {
            mImageUri = data.getData();
            Picasso.get().load(mImageUri).into(uploadImageView);

        }
    }

    private String getFileExtension(Uri uri) {

        ContentResolver contentResolver = requireActivity().getContentResolver();
        MimeTypeMap mime = MimeTypeMap.getSingleton();
        return mime.getExtensionFromMimeType(contentResolver.getType(uri));
    }

    private void uploadToFirebase(Uri mImageUri) {
        if (mImageUri != null) {
            final ProgressDialog progressDialog = new ProgressDialog(getActivity());
            progressDialog.setTitle("Uploading...");
            progressDialog.show();

            StorageReference reference = storageReference.child(System.currentTimeMillis()
                    + "." + getFileExtension(mImageUri));
            reference.putFile(mImageUri)
                    .addOnSuccessListener(taskSnapshot -> {
                        progressDialog.dismiss();
                        Toast.makeText(getActivity(), "Saved Succesfully", Toast.LENGTH_SHORT).show();
                        reference.getDownloadUrl()
                                .addOnSuccessListener(uri -> {
                                    Upload upload = new Upload(uri.toString());
                                    String uploadId = databaseReference.push().getKey();
                                    databaseReference.child(uploadId).setValue(upload);
                                });
                    })
                    .addOnProgressListener(snapshot -> {
                        double progress = (100.0 * snapshot.getBytesTransferred() / snapshot
                                .getTotalByteCount());
                        progressDialog.setMessage("Uploaded " + (int) progress + "%");
                    })
                    .addOnFailureListener(e -> {
                        progressDialog.dismiss();
                        Toast.makeText(getActivity(), "Error Ocurred" + e.getMessage(), Toast.LENGTH_SHORT).show();
                    });


        }
    }
} 

A potential workaround is to upload a byte array into firebase; so when taking a photo by camera, you can get the Bitmap byte array from the intent received in onActivityResult() and eventually upload the byte array to the firebase storage using ref.putBytes() method.

This can be done in several steps like in below:

Here I'm assuming that the requestCode for camera in onActivityResult() is 1:

final int FROM_GALLERY = 0;
final int FROM_CAMERA = 1;

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

    
    if (resultCode == RESULT_OK && data != null) {

        switch (requestCode) {
        
            case FROM_GALLERY:
            
                // Handle image from the gallery
                filePath = data.getData();
                break;


            case FROM_CAMERA:
            
                // Handle image from the camera

                if (data.getExtras() != null) {
                    Bitmap photoBitmap = (Bitmap) data.getExtras().get("data");
                    byte[] bitmapBytes = getBytesFromBitmap(bitmap, 100);
                    uploadToFirebase(bitmapBytes);
                    
                }

                break;
        }

    }
}


// convert from bitmap to byte array
public static byte[] getBytesFromBitmap(Bitmap bitmap, int quality) {
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG, quality, stream);
    // bitmap.compress(Bitmap.CompressFormat.PNG, quality, stream); // According to the needed quality
    return stream.toByteArray();
}   



public void uploadToFirebase(bytes[] bytes) {
    StorageReference ref = .... 
    ref.putBytes(bytes)
        .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {

            }

        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception exception) {
            }

        }).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {

            }
        }); 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM