7

I created a simple application which crop the image . Now I want to save this image to the Fire base .

photo.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            //Intent imageDownload = new 
Intent(Intent.ACTION_PICK,MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
      Intent imageDownload=new Intent();
      imageDownload.setAction(Intent.ACTION_GET_CONTENT);
      imageDownload.setType("image/*");
      imageDownload.putExtra("crop", "true");
      imageDownload.putExtra("aspectX", 1);
      imageDownload.putExtra("aspectY", 1);
      imageDownload.putExtra("outputX", 200);
      imageDownload.putExtra("outputY", 200);
      imageDownload.putExtra("return-data", true);
      startActivityForResult(imageDownload, GALLERY_REQUEST_CODE);


        }
    });
 }
  @Override
protected void onActivityResult(int requestCode, int resultCode, Intent 
  data) {
    super.onActivityResult(requestCode, resultCode, data);
    if(requestCode == GALLERY_REQUEST_CODE && resultCode == RESULT_OK && 
   data != null) {
        Bundle extras = data.getExtras();
        image = extras.getParcelable("data");
        photo.setImageBitmap(image);

   }






}

How to save this image to the Firebase . I tried many tutorial but could not succeed . Please verify with simple code .

adjuremods
  • 2,938
  • 2
  • 12
  • 17
wiki wi
  • 91
  • 1
  • 1
  • 5

3 Answers3

21

you must first add the dependencies for Firebase Storage to your build.gradle file:

compile 'com.google.firebase:firebase-storage:10.0.1'
compile 'com.google.firebase:firebase-auth:10.0.1'

then create an instance of FirebaseStorage:

FirebaseStorage storage = FirebaseStorage.getInstance();

To upload a file to Firebase Storage, you first create a reference to the full path of the file, including the file name.

// Create a storage reference from our app
StorageReference storageRef = storage.getReferenceFromUrl("gs://<your-bucket-name>");

// Create a reference to "mountains.jpg"
StorageReference mountainsRef = storageRef.child("mountains.jpg");

// Create a reference to 'images/mountains.jpg'
StorageReference mountainImagesRef = storageRef.child("images/mountains.jpg");

// While the file names are the same, the references point to different files
mountainsRef.getName().equals(mountainImagesRef.getName());    // true
mountainsRef.getPath().equals(mountainImagesRef.getPath());    // false

Once you've created an appropriate reference, you then call the putBytes(), putFile(), or putStream() method to upload the file to Firebase Storage.

The putBytes() method is the simplest way to upload a file to Firebase Storage. putBytes() takes a byte[] and returns an UploadTask that you can use to manage and monitor the status of the upload.

// Get the data from an ImageView as bytes
imageView.setDrawingCacheEnabled(true);
imageView.buildDrawingCache();
Bitmap bitmap = imageView.getDrawingCache();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] data = baos.toByteArray();

UploadTask uploadTask = mountainsRef.putBytes(data);
uploadTask.addOnFailureListener(new OnFailureListener() {
    @Override
    public void onFailure(@NonNull Exception exception) {
        // Handle unsuccessful uploads
    }
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
    @Override
    public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
        // taskSnapshot.getMetadata() contains file metadata such as size, content-type, and download URL.
        Uri downloadUrl = taskSnapshot.getDownloadUrl();
    }
});
  • and if i want to convert this bitmap to uri so then how can be? – wiki wi Nov 30 '16 at 10:56
  • 1
    public Uri getImageUri(Context inContext, Bitmap inImage) { ByteArrayOutputStream bytes = new ByteArrayOutputStream(); inImage.compress(Bitmap.CompressFormat.PNG,100, bytes); String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null); return Uri.parse(path); } – Akshay Kumar Both May 08 '18 at 07:07
  • 1
    You are a life-saver! Makes it so much easier when I can convert to Bitmap image to bytes – dave o grady Apr 17 '20 at 00:02
4

Firebase does not support binary data, so you need to convert the image data to base64 or use Firebase Storage

Method 1 ( Recommended )

 sref = FirebaseStorage.getInstance().getReference(); // please go to above link and setup firebase storage for android

 public void uploadFile(Uri imagUri) {
    if (imagUri != null) {

        final StorageReference imageRef = sref.child("android/media") // folder path in firebase storage
                .child(imagUri.getLastPathSegment());

        photoRef.putFile(imagUri)
                .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                    @Override
                    public void onSuccess(UploadTask.TaskSnapshot snapshot) {
                        // Get the download URL
                        Uri downloadUri = snapshot.getMetadata().getDownloadUrl();
                        // use this download url with imageview for viewing & store this linke to firebase message data

                    }
                })
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception exception) {
                         // show message on failure may be network/disk ?
                    }
                });
    }
}

Method 2

for small images we can still go with this solution, there is firebase field value limitations(1MB field value) check official doc for details

public void getImageData(Bitmap bmp) {  

  ByteArrayOutputStream bao = new ByteArrayOutputStream();
  bmp.compress(Bitmap.CompressFormat.PNG, 100, bao); // bmp is bitmap from user image file
  bmp.recycle();
  byte[] byteArray = bao.toByteArray();
  String imageB64 = Base64.encodeToString(byteArray, Base64.URL_SAFE); 
  //  store & retrieve this string which is URL safe(can be used to store in FBDB) to firebase
  // Use either Realtime Database or Firestore
  }
Renjith Thankachan
  • 4,178
  • 1
  • 30
  • 47
  • why is method 2 not recommended? – Arjun Dec 22 '19 at 09:57
  • 1
    It's because of the size! for small images we can still go with this, check this for firebase limitations(1MB field value) https://firebase.google.com/docs/firestore/quotas – Renjith Thankachan Dec 22 '19 at 10:01
  • Yeah, thanks! I used your method 2 and got the imageB64 string. But the string has "/" character in it. Can I store this string to Firebase Database? According to this https://stackoverflow.com/a/41142720/9924372 I won't be able to store it in FBDB – Arjun Dec 22 '19 at 10:05
  • 1
    Updated the answer with details, have a great coding day :) – Renjith Thankachan Dec 22 '19 at 10:06
  • In recent version of Firebase Storage API, the getDownloadUrl() method using taskSnapshot object has changed. now you can use, snapshot.getMetadata().getReference().getDownloadUrl().toString() – Rajeev Jayaswal May 31 '20 at 14:32
  • Please append these changes in the answer (Do not edit the original answer, just append the changes with relevent urls/docs) @RajeevJayaswal – Renjith Thankachan May 31 '20 at 14:41
  • 1
    @RenjithThankachan So you say that in order to use Base64, we need to setup the Realtime Database and not the Cloud Firestore? – H.Karatsanov Jun 23 '20 at 14:57
  • 1
    @H.Karatsanov once base64 is set, you can store it any service firestore or realtimedatabase – Renjith Thankachan Jun 25 '20 at 15:49
0

"firebase-storage 16.0.1"

task.getDowloadUrl() not defined. You can use this i check , working perfectly.

 private void firebaseUploadBitmap(Bitmap bitmap) {
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
    byte[] data = stream.toByteArray();
    StorageReference imageStorage = storage.getReference();
    StorageReference imageRef = imageStorage.child("images/" + "imageName");

    Task<Uri> urlTask = imageRef.putBytes(data).continueWithTask(task -> {
        if (!task.isSuccessful()) {
            throw task.getException();
        }

        // Continue with the task to get the download URL
        return imageRef.getDownloadUrl();
    }).addOnCompleteListener(task -> {
        if (task.isSuccessful()) {
            Uri downloadUri = task.getResult();
            String uri = downloadUri.toString();
            sendMessageWithFile(uri);
        } else {
            // Handle failures
            // ...
        }
        progressBar.setVisibility(View.GONE);
    });
    
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == PICK_IMAGE && resultCode == Activity.RESULT_OK) {
        //      Bitmap imageBitmap = data.getData() ;
        Bitmap photo = (Bitmap) data.getExtras().get("data");
        if (photo != null)
            firebaseUploadBitmap(photo);

    } else if (requestCode == SELECT_IMAGE && resultCode == Activity.RESULT_OK) {

        Uri uri = data.getData();
        if (uri != null)
            firebaseUploadImage(uri);
    }

}
Yasin Ege
  • 605
  • 4
  • 14