2016-11-30 7 views
-2

이미지를 자르는 간단한 응용 프로그램을 만들었습니다. 이제이 이미지를 Fire Base에 저장하려고합니다.비트 맵을 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

중포 기지 바이너리 데이터를 지원하지 않는, 그래서 당신은 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 
    } 
에게 64 기수에 이미지 데이터를 변환하거나 사용할 필요가
1

먼저 Firebase 저장소에 대한 종속성을 추가해야합니다 당신의 build.gradle 파일 :

FirebaseStorage storage = FirebaseStorage.getInstance(); 

, 당신은 먼저 파일의 전체 경로에 대한 참조를 만들, 중포 기지 저장 장치에 파일을 업로드 포함하려면 :

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

는 FirebaseStorage의 인스턴스를 생성 파일명

// 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 Storage에 파일을 업로드하는 가장 간단한 방법입니다. 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

를 ** 일어나지 않았다 그리고 난 그럼 열린 우리당이 비트 맵을 변환 할 경우 어떻게 할 수 있습니까? –