[英]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.我正在尝试用相机拍照并将其上传到 Firebase。 I'm using a AlertDialog to ask the user if they want to use the camera or select image from gallery.
我正在使用 AlertDialog 询问用户是否要使用相机或画廊中的 select 图像。 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;一个潜在的解决方法是将字节数组上传到 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.因此,当通过相机拍照时,您可以从
onActivityResult()
中接收到的意图中获取 Bitmap 字节数组,并最终使用ref.putBytes()
方法将字节数组上传到 firebase 存储。
This can be done in several steps like in below:这可以通过如下几个步骤完成:
Here I'm assuming that the requestCode
for camera in onActivityResult()
is 1:这里我假设
onActivityResult()
中相机的requestCode
为 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) {
}
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.