[英]How to capture image using camera and send to firebase
我正在使用相机捕获图像,并想发送到Firebase存储。 但是到三三天我就出错了。 我被卡住了。 当我激发意图时,它捕获图像,但是在onActivityresult中,它返回请求代码= 1,结果代码= -1。 这是我的代码
捐赠活动:
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);
}
}
}
}
我在等于0的活动结果代码中收到错误。
我的例子希望您能理解。
@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();
}
});
}
}
BTW AFAIK,
public static final int RESULT_OK = -1;
public static final int RESULT_CANCELED = 0;
如果您使用的是Windows计算机,只需在RESULT_OK上按ctrl + B **因此,也许您正在以某种方式取消活动,直到该活动完成。 我做了类似的事情。 拍摄完视频/照片后,请等待操作系统显示对勾或选择该照片的内容。 这是我的代码,如果有帮助。
尝试这个
/**
* 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中,执行以下操作。 您做了一个重命名文件的功能。 我猜不需要。 该文件会自动存储在手机的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());
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.