如何使用相机捕获图像并发送到 firebase
How to capture image using camera and send to firebase
我正在使用相机拍摄图像并想发送到 firebase 存储。但是我在 3 三天前收到错误。我被困在上面了。当我启动 Intent 时它捕获图像,但在 onActivityresult 中它 returns 请求代码=1 和结果代码=-1。这是我的代码
捐款Activity:
package com.example.manzoorhussain.kindnessapp;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Parcelable;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DonationActivity extends AppCompatActivity {
private Button mUploadBtn;
private ImageView mImageView;
private final static int CAMERA_REQUEST_CODE = 1;
private StorageReference mstorage;
ProgressDialog progressDialog;
Uri photoURI;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_donation);
mUploadBtn = (Button) findViewById(R.id.upload);
mImageView = (ImageView) findViewById(R.id.imageView);
progressDialog = new ProgressDialog(this);
mstorage = FirebaseStorage.getInstance().getReference();
mUploadBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
dispatchTakePictureIntent();
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_REQUEST_CODE && resultCode == RESULT_OK) {
Toast.makeText(this, "" + photoURI, Toast.LENGTH_SHORT).show();
progressDialog.setMessage("Uploading...");
progressDialog.show();
Uri uri = data.getData();
StorageReference filepath = mstorage.child("Photos").child(uri.getLastPathSegment());
filepath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(DonationActivity.this, "Upload Successful!", Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(DonationActivity.this, "Upload Failed!", Toast.LENGTH_SHORT).show();
}
});
}
}
String mCurrentPhotoPath;
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = image.getAbsolutePath();
return image;
}
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File...
}
// Continue only if the File was successfully created
if (photoFile != null) {
photoURI = FileProvider.getUriForFile(this,
"com.example.android.fileprovider",
photoFile);
//takePictureIntent.setData(photoURI);
// takePictureIntent.putExtra("imageUri", photoURI.toString());
takePictureIntent.putExtra("imageUri", photoURI.toString());
// takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, CAMERA_REQUEST_CODE);
}
}
}
}
我在 activity 结果代码中收到错误,结果代码为零。
我的例子希望你能看懂。
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GALLERY_INTENT && resultCode == RESULT_OK){
Uri uri = data.getData();
progressDialog.setMessage(UPLOADING);
progressDialog.show();
StorageReference filePath = storageRef.child(STORAGE_FOLDER_NAME).child(recipeTitle.getText().toString());
filePath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(CreateNewRecipeActivity.this, UPLOAD_COMPLETE, Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
}
});
}
}
顺便说一句,
public static final int RESULT_OK = -1;
public static final int RESULT_CANCELED = 0;
如果您在 Windows 机器上,只需在 RESULT_OK 上按 ctrl + B**
因此,也许您在 activity 完成之前以某种方式取消了 activity。我做过类似的事情。在您的 video/photo 被拍摄后,等待 OS 显示对 select 拍摄的照片的勾号或其他内容。如果有帮助,这是我的代码。
试试这个
/**
* Upload a video directly by recording it using camera
* You can do image/video whatever you require
*/
private void recordVideo() {
Intent recordVideoIntent = new Intent();
recordVideoIntent.setAction(MediaStore.ACTION_VIDEO_CAPTURE);
if (recordVideoIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(recordVideoIntent, UPLOAD_VIDEO_CAMERA);
}
}
//在加载器或异步任务中进行网络调用
getLoaderManager().initLoader(0, null, UploadVideo.this);
//在你的 AsyncTask 或 Loader 中,做这样的事情。您创建了一个重命名文件的函数。我猜这是不需要的。该文件自动存储在您的 phone AFAIK 中。关于 Firebase Storage 中的文件名,只需使用类似这样的东西
//Upload the video to storage
StorageReference mFirebaseStorageRef = FirebaseStorage.getInstance().getReference();
mFirebaseStorageRef
.child(String.valueOf(mCurrentUser.getEmail() + new Date().getTime()))
.putFile(videoData).
addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
try {
//MAYBE UPDATE IT SOMEPLACE IN DATABASE AS WELL
HashMap<String, String> city_Obj = new HashMap<String,String>();
city_Obj.put("VIDEO_URL", downloadUrl);
city_Obj.put("VIDEO_NAME", nameOfVideo);
city_Obj.put("VIDEO_DESC", descriptionOfVideo);
dbRef.child("CITIES").child(spinnerCityName).push().setValue(city_Obj);
} catch (Exception e) {
e.printStackTrace();
Log.e("DB ERROR", e.getMessage());
}
我正在捕获图像,就像您在上传之前将图像保存到文件系统一样,但是使用 mCurrentPhotoPath 加载位图。然后将位图转换为字节并从那里上传到 Firebase 存储。
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_TAKE_PHOTO && resultCode == RESULT_OK) {
BitmapFactory.Options options = new BitmapFactory.Options();
Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, options);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
StorageReference reference = FirebaseStorage.getInstance().getReference().child("photo");
UploadTask uploadTask = reference.putBytes(imageBytes);
uploadTask.addOnSuccessListener(new
OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Log.d("UploadComplete", "Image successfully uploaded URL: %s", taskSnaphot.getDownloadUrl().toString());
}
});
} else if (resultCode == RESULT_CANCELED) {
onCancel();
}
}
private File createImageFile() throws IOException {
String ts = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String filename = String.format("JPEG_%s_", ts);
File storageDir = getActivity().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(filename, ".jpg", storageDir);
mCurrentPhotoPath = image.getAbsolutePath();
return image;
}
为了在我的应用程序中进一步分解它,我首先在 ImageView 中显示图像,然后在上传时像这样将其转换为 byte[]。
Bitmap bitmap = ((BitmapDrawable) mImageView.getDrawable().getBitmap();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
然后上传到 Firebase。
StorageReference reference = FirebaseStorage.getInstance().getReference().child("photo");
UploadTask uploadTask = reference.putBytes(imageBytes);
uploadTask.addOnSuccessListener(new
OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Log.d("UploadComplete", "Image successfully uploaded URL: %s", taskSnaphot.getDownloadUrl().toString());
}
});
我正在使用相机拍摄图像并想发送到 firebase 存储。但是我在 3 三天前收到错误。我被困在上面了。当我启动 Intent 时它捕获图像,但在 onActivityresult 中它 returns 请求代码=1 和结果代码=-1。这是我的代码
捐款Activity:
package com.example.manzoorhussain.kindnessapp;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Parcelable;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DonationActivity extends AppCompatActivity {
private Button mUploadBtn;
private ImageView mImageView;
private final static int CAMERA_REQUEST_CODE = 1;
private StorageReference mstorage;
ProgressDialog progressDialog;
Uri photoURI;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_donation);
mUploadBtn = (Button) findViewById(R.id.upload);
mImageView = (ImageView) findViewById(R.id.imageView);
progressDialog = new ProgressDialog(this);
mstorage = FirebaseStorage.getInstance().getReference();
mUploadBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
dispatchTakePictureIntent();
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_REQUEST_CODE && resultCode == RESULT_OK) {
Toast.makeText(this, "" + photoURI, Toast.LENGTH_SHORT).show();
progressDialog.setMessage("Uploading...");
progressDialog.show();
Uri uri = data.getData();
StorageReference filepath = mstorage.child("Photos").child(uri.getLastPathSegment());
filepath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(DonationActivity.this, "Upload Successful!", Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(DonationActivity.this, "Upload Failed!", Toast.LENGTH_SHORT).show();
}
});
}
}
String mCurrentPhotoPath;
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = image.getAbsolutePath();
return image;
}
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File...
}
// Continue only if the File was successfully created
if (photoFile != null) {
photoURI = FileProvider.getUriForFile(this,
"com.example.android.fileprovider",
photoFile);
//takePictureIntent.setData(photoURI);
// takePictureIntent.putExtra("imageUri", photoURI.toString());
takePictureIntent.putExtra("imageUri", photoURI.toString());
// takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, CAMERA_REQUEST_CODE);
}
}
}
}
我在 activity 结果代码中收到错误,结果代码为零。
我的例子希望你能看懂。
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GALLERY_INTENT && resultCode == RESULT_OK){
Uri uri = data.getData();
progressDialog.setMessage(UPLOADING);
progressDialog.show();
StorageReference filePath = storageRef.child(STORAGE_FOLDER_NAME).child(recipeTitle.getText().toString());
filePath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(CreateNewRecipeActivity.this, UPLOAD_COMPLETE, Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
}
});
}
}
顺便说一句,
public static final int RESULT_OK = -1;
public static final int RESULT_CANCELED = 0;
如果您在 Windows 机器上,只需在 RESULT_OK 上按 ctrl + B** 因此,也许您在 activity 完成之前以某种方式取消了 activity。我做过类似的事情。在您的 video/photo 被拍摄后,等待 OS 显示对 select 拍摄的照片的勾号或其他内容。如果有帮助,这是我的代码。
试试这个
/**
* Upload a video directly by recording it using camera
* You can do image/video whatever you require
*/
private void recordVideo() {
Intent recordVideoIntent = new Intent();
recordVideoIntent.setAction(MediaStore.ACTION_VIDEO_CAPTURE);
if (recordVideoIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(recordVideoIntent, UPLOAD_VIDEO_CAMERA);
}
}
//在加载器或异步任务中进行网络调用
getLoaderManager().initLoader(0, null, UploadVideo.this);
//在你的 AsyncTask 或 Loader 中,做这样的事情。您创建了一个重命名文件的函数。我猜这是不需要的。该文件自动存储在您的 phone AFAIK 中。关于 Firebase Storage 中的文件名,只需使用类似这样的东西
//Upload the video to storage
StorageReference mFirebaseStorageRef = FirebaseStorage.getInstance().getReference();
mFirebaseStorageRef
.child(String.valueOf(mCurrentUser.getEmail() + new Date().getTime()))
.putFile(videoData).
addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
try {
//MAYBE UPDATE IT SOMEPLACE IN DATABASE AS WELL
HashMap<String, String> city_Obj = new HashMap<String,String>();
city_Obj.put("VIDEO_URL", downloadUrl);
city_Obj.put("VIDEO_NAME", nameOfVideo);
city_Obj.put("VIDEO_DESC", descriptionOfVideo);
dbRef.child("CITIES").child(spinnerCityName).push().setValue(city_Obj);
} catch (Exception e) {
e.printStackTrace();
Log.e("DB ERROR", e.getMessage());
}
我正在捕获图像,就像您在上传之前将图像保存到文件系统一样,但是使用 mCurrentPhotoPath 加载位图。然后将位图转换为字节并从那里上传到 Firebase 存储。
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_TAKE_PHOTO && resultCode == RESULT_OK) {
BitmapFactory.Options options = new BitmapFactory.Options();
Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, options);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
StorageReference reference = FirebaseStorage.getInstance().getReference().child("photo");
UploadTask uploadTask = reference.putBytes(imageBytes);
uploadTask.addOnSuccessListener(new
OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Log.d("UploadComplete", "Image successfully uploaded URL: %s", taskSnaphot.getDownloadUrl().toString());
}
});
} else if (resultCode == RESULT_CANCELED) {
onCancel();
}
}
private File createImageFile() throws IOException {
String ts = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String filename = String.format("JPEG_%s_", ts);
File storageDir = getActivity().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(filename, ".jpg", storageDir);
mCurrentPhotoPath = image.getAbsolutePath();
return image;
}
为了在我的应用程序中进一步分解它,我首先在 ImageView 中显示图像,然后在上传时像这样将其转换为 byte[]。
Bitmap bitmap = ((BitmapDrawable) mImageView.getDrawable().getBitmap();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
然后上传到 Firebase。
StorageReference reference = FirebaseStorage.getInstance().getReference().child("photo");
UploadTask uploadTask = reference.putBytes(imageBytes);
uploadTask.addOnSuccessListener(new
OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Log.d("UploadComplete", "Image successfully uploaded URL: %s", taskSnaphot.getDownloadUrl().toString());
}
});