Android Firebase-将图像从可绘制图像上传到存储

时间:2018-12-14 13:56:48

标签: android firebase firebase-storage

我正在尝试从可绘制文件夹中获取图像并将其保存在Firebase Storage中。 要使用UploadTask保存图像,它需要一个Uri文件。 可绘制的图像为int。反正有将int转换成Uri吗?

请查看我的代码

 private void saveProfileImgToStorage(final User user) {
    storageRef = FirebaseStorage.getInstance().getReference();

    StorageReference userImgProfile = storageRef.child("/usersProfiles/" + currentUser.getUid() +"/profile_image");
    UploadTask uploadTask;

          //What should i do here??
          //This is the path of the image "R.drawable.ic_account"
    uploadTask = userImgProfile.putFile();

    uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
        @Override
        public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
            Uri firebaseURL = taskSnapshot.getDownloadUrl();
            user.setProfilePic(firebaseURL.toString());
            uploadToFirebaseDatabase(user);
        }
    }).addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception e) {
            Log.d(TAG,e.getMessage().toString());
        }
    });
}

修改

找到了解决方案

   //This how i should write it - and now it works!
  Uri imageUri = Uri.parse("android.resource://"+ R.class.getPackage().getName()+"/"+R.drawable.profile_image);
   UploadTask uploadTask;

    uploadTask = userImgProfile.putFile(imageUri);

1 个答案:

答案 0 :(得分:2)

要从存储到drawable的图像中获取uri,只需执行此操作

Uri imageUri = Uri.parse("android.resource://your.package.name/" + R.drawable.ic_account);

更清洁

 Uri imageUri = Uri.parse("android.resource://" + context.getPackageName() + 
 R.drawable.ic_account);

如果您从片段中引用活动或context,则this可以是getActivity()

要将其上传到Firebase,您需要执行此操作

File file = new File(imageUri.getPath());

然后

uploadTask = userImgProfile.putFile(file);