Capturing Image from Camera and Upload to Firebase
I have found a solution to my question, i realized that i can get my captured data using the function of data.getData() instead of using the Bitmap function:
mImageUri = data.getData();
mSelectImage.setImageURI(mImageUri);
Also, Previously i did not realized that my 'crop' function could not work because i am missing of:
mImageUri = resultUri;
I realized that there is an issue that if i did not crop my captured image, the fire-base could not handle the high resolution (Or storage size? and it will be loading very slow/image did not appear), This can be resolve by the 'cropping' function.
The final code is stated below: Thanks all for your help.
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();
}
}
}
}
![Emilyy Lim](https://i.stack.imgur.com/oL7eH.png?s=256&g=1)
Emilyy Lim
Updated on June 16, 2022Comments
-
Emilyy Lim about 2 years
I am working on a simple blog app that allows the user to upload photo from phone gallery and descriptions to the Firebase Server. I am trying to modify my current project to allow the user to capture photo from camera and uploading it to the firebase server.
Currently, I am able to display the image that i have captured into imagebutton, however i am unable to post my image to the firebase server (The "submit post" button does not react to my onclick function).
I am suspecting there is some error in my startPosting() function or i did not encode the image correctly? Please help.
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(); } } } }
-
Emilyy Lim over 7 yearsI initialize, using private Uri mImageUri = null; but it still give me the same error
-
Emilyy Lim over 7 yearsYes i set it to private Uri mImageUri = null; is this the cause of my error? if so, what should i change it do?
-
yotam hadas over 7 yearsI did something like what you trying to achive, when I will get home I will upload the relevant part of the code.
-
yotam hadas over 7 yearsIn general you need to get the file path, but getting the url from data might return null (depand on the android version). if you use version 6 or below you can use: mImageUri = data.getData(); If you want to make sure you get Uri I would check if the phone run android 6 or above and if it does add extra to the capture intent adding file location and get the uri from the file.
-
yotam hadas over 7 yearsI edited my answer, I hope its will help you. the thing is that on phone below version SDK 24 you can just use mImageUri = data.getData() in the onActivityResault but above that it return only a thumbnail and not the entire file (not sure why) so you telll the system WHERE to save the capture picture and then use the file + FileProvider ot get the URI
-
mol over 7 yearsExactly, you initialized it with null, and then check if it is null. You never overwrite null value, so condition mImageUri !=null never true.
-
Emilyy Lim over 7 yearsi do not get the part whereby i have to put externalpath, where do i place the code? I went to search online developer.android.com/training/camera/photobasics.html i could not understand where should i place the code too.
-
Mridul Agarwal almost 6 yearsi am getting error in getdownloadurl() how do i solve it