gpt4 book ai didi

android - 将相机或图库中的图像上传到 FirebaseStorage

转载 作者:行者123 更新时间:2023-11-29 22:47:56 26 4
gpt4 key购买 nike

我有以下代码,以便在我从图库中选择/拍照后在 ImageView 中显示图像:

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {

super.onActivityResult(requestCode, resultCode, data);
if (resultCode == this.RESULT_CANCELED) {
return;
}
if (requestCode == GALLERY) {
if (data != null) {
Uri contentURI = data.getData();
try {
FixBitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), contentURI);
ShowSelectedImage.setImageBitmap(FixBitmap);

} catch (IOException e) {
e.printStackTrace();
Toast.makeText(ProfileActivity.this, "Failed!", Toast.LENGTH_SHORT).show();
}
}

} else if (requestCode == CAMERA) {
FixBitmap = (Bitmap) data.getExtras().get("data");
ShowSelectedImage.setImageBitmap(FixBitmap);
}
}

现在,我希望将此图像保存在当前用户的 uid 下的 FirebaseStorage 中。

所以我知道我应该使用一些东西:

String userUid = FirebaseAuth.getInstance().getCurrentUser().getUid();

但是,我如何在我的存储中进行此上传?我的最终目标是,一旦用户登录,它将自动显示存储中的个人资料图片,如果没有照片或用户拍摄了新照片,它将更新存储中的照片。

我在类型方面也遇到了问题,因为 putBytes 需要 BytesArray 并且我得到的结果是 Bitmap 左右。

谢谢。

最佳答案

以下代码将帮助您使用当前用户的用户 ID 将图像存储在 images 文件夹下。您有图像位置,因此 Firebase 将从存储中选择图像。

uploadImg.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(contentURI != null) {

StorageReference childRef = storageRef.child("/images/"+uid+".jpg");

//uploading the image
UploadTask uploadTask = childRef.putFile(contentURI);
uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(MainActivity.this, "Upload successful", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(MainActivity.this, "Upload Failed -> " + e, Toast.LENGTH_SHORT).show();
}
});
}
else {
Toast.makeText(MainActivity.this, "Select an image", Toast.LENGTH_SHORT).show();
}
}
});

声明变量:

StorageReference storageRef;

在 onCreateView 中:

storageRef = storage.getReference();

让它公开声明,否则它会再次抛出错误

关于android - 将相机或图库中的图像上传到 FirebaseStorage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58166983/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com