2016-11-30 52 views
-2

我創建了一個裁剪圖像的簡單應用程序。現在我想將這張圖片保存到Fire基地。如何將位圖保存到Firebase

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); 

    } 






} 

如何將此圖片保存到Firebase。我嘗試了很多教程,但無法成功。請用簡單的代碼進行驗證。

+0

*我試過很多教程,但未能成功,* .... **鏈接或它沒有發生** – Selvin

回答

0

火力地堡不支持二進制數據,所以你需要將圖像數據轉換爲base64或使用Firebase Storage

方法1(推薦)

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 ? 
        } 
       }); 
    } 
} 

方法2

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 = bYtE.toByteArray(); 
    String imageB64 = Base64.encodeToString(byteArray, Base64.DEFAULT); 
    // store & retrieve this string to firebase 
    } 
1

您必須先添加Firebase存儲的依存關係您的build.gradle文件:

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

然後創建FirebaseStorage的一個實例:

FirebaseStorage storage = FirebaseStorage.getInstance(); 

要上傳文件到火力地堡寄存,首先要創建該文件的完整路徑的引用,其中包括文件名。

// 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 

一旦你創建了一個合適的參考,你再調用putBytes(),PUTFILE(),或putStream()方法來把文件上傳到火力地堡存儲。

putBytes()方法是將文件上傳到Firebase存儲的最簡單方法。 putBytes()需要一個byte []並返回一個UploadTask,您可以使用它來管理和監視上載狀態。

// 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(); 
    } 
}); 
+0

如果我想這個位圖轉換爲URI,這樣的話怎麼可能呢? –