使用Glide和Firebase Android存储和显示图像

4

我正在尝试使用Glide和Firebase上传和显示个人资料照片。上传部分已经成功工作。但是,如果我尝试从数据库加载该图片,则会显示空白。我的目的是在用户进入活动时加载资料照片,并且他可以轻触现有照片并根据自己的意愿更改。

我的代码:

public class User extends AppCompatActivity {

    private ImageView imageView;
    private Uri filePath;
    private final int PICK_IMAGE_REQUEST = 71;
    StorageReference storageReference;

    private void loadImage(){

        Bundle bundle = getIntent().getExtras();
        assert bundle != null;
        final String retrievedName = bundle.getString("Name");

        // Reference to an image file in Cloud Storage
        StorageReference storageReference  = FirebaseStorage.getInstance().getReference().child(retrievedName).child("images/profile_image");
        imageView = findViewById(R.id.profile_image);

    // Load the image using Glide
        Glide.with(User.this.getApplicationContext())
                .load(storageReference)
                .into(imageView );
    }


    private void uploadImage() {

        if(filePath != null)
        {

            Bundle bundle = getIntent().getExtras();
            assert bundle != null;
            final String retrievedName = bundle.getString("Name");

            storageReference = FirebaseStorage.getInstance().getReference();

            StorageReference ref = storageReference.child(retrievedName).child("images/profile_image");
            ref.putFile(filePath)
                    .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                        @Override
                        public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                            Toast.makeText(User.this, "Uploaded", Toast.LENGTH_SHORT).show();
                        }
                    })
                    .addOnFailureListener(new OnFailureListener() {
                        @Override
                        public void onFailure(@NonNull Exception e) {
                            Toast.makeText(User.this, "Failed "+e.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    });
        }
    }

    private void chooseImage() {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK
                && data != null && data.getData() != null )
        {
            filePath = data.getData();
            try {
                Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
                imageView.setImageBitmap(bitmap);

                uploadImage();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user);
        imageView = findViewById(R.id.profile_image);

        loadImage();

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

                    chooseImage();
            }
        });
    }

}
2个回答

3
最终我找到了解决方案。 在上传部分,我将url添加到实时数据库中。
url_db = FirebaseDatabase.getInstance().getReference().child(retrievedName).child("Url");
        StorageReference ref = FirebaseStorage.getInstance().getReference().child(retrievedName).child("images/profile_image");
        ref.putFile(filePath)
                .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                    @Override
                    public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                        @SuppressWarnings("VisibleForTests") Uri downloadUrl =
                                taskSnapshot.getDownloadUrl();
                        uploadImageUrl = downloadUrl.toString();

                        url_db.setValue(uploadImageUrl);
                    }
                })
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        Toast.makeText(User.this, "Failed " + e.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                });

在加载时,我从数据库中使用了这个URL,并在Glide中使用。

imageView = findViewById(R.id.profile_image);

    url_db = FirebaseDatabase.getInstance().getReference().child(retrievedName).child("Url");

    url_db.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

            String url = dataSnapshot.getValue(String.class);

            if(url!= null){

                imageLoad.setVisibility(View.VISIBLE);


                Glide.with( User.this)
                        .load(url)
                        .into(imageView);

                imageLoad.setVisibility(View.INVISIBLE);

            }

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

感谢大家的支持。

我已经寻找这个答案几个小时了。谢谢! - lcompare

1
根据官方Firebase文档这里的说明,您应该使用getDownloadURL()获取照片的下载链接,以便将其传递给Glide库,这样Glide就可以显示您的图像。
在此行中添加getDownloadUrl();
    StorageReference ref = storageReference.child(retrievedName).child("images/profile_image").getDownloadUrl();

然后使用Glide调用您的图像。
// Load the image using Glide
Glide.with(this /* context */)
        .using(new FirebaseImageLoader())
        .load(ref)
        .into(imageView);

为了使用FirebaseImageLoader(),只需记得在您的gradle中添加以下内容。
dependencies {
    // FirebaseUI Storage only
    compile 'com.firebaseui:firebase-ui-storage:0.6.0'
}

此外,还可以关注这个 GitHub 链接,了解如何从StorageReference中加载图像。
另一种更简单的方法是获取DownloadUrl并在glide中使用它。
ref.putFile(filePath)
                .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                    @Override
                    public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                         @SuppressWarnings("VisibleForTests") Uri downloadUrl = 
                     taskSnapshot.getDownloadUrl();
                    uploadImageUrl = downloadUrl.toString();
                Toast.makeText(getApplicationContext(), "url to your file..."+uploadImageUrl, Toast.LENGTH_SHORT).show();
                    }
                })
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        Toast.makeText(User.this, "Failed "+e.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                });

uploadImageUrl是一个全局变量,类型为private String

然后只需使用Glide将该图片URL加载到您的imageView中即可。

Glide.with(this /* your_context */)
    .load(uploadImageUrl)
    .centerCrop()
    .into(imageView)

在这行代码中,我遇到了错误:StorageReference ref = storageReference.child(retrievedName).child("images/profile_image").getDownloadUrl();还有一个问题是.using无法解析。 - Dipin K G
但我需要在 Activity 开始时的加载值…而不是上传后。在上传下一张图片之前先加载该图片。 - Dipin K G
所以,您应该首先将图像存储到数据库中,并使用下载URL访问它,如果您的第一张图像已经存储,则我提供的链接应该会帮助您。 - Gastón Saillén

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接