如何从Firebase存储中设置图像视图?

时间:2018-12-04 16:40:27

标签: java android firebase firebase-storage

我从文档和在线帮助中都尝试了所有示例,但是我无法获得存储中要显示在图像视图上的简单图像。

假设我在名为“图片”的文件夹中有图片,因此photo1.jpg存储在引用中:

StorageReference storageReference = FirebaseStorage.getInstance().getReference();
StorageReference photoReference= storageReference.child("pictures/photo1.jpg");

但是如何设置它,并将其内容替换为我通过id找到的现有图像视图:

ImageView photoView= (ImageView) findViewById(R.id.photo_view);

在获取Uri的侦听器上我一直失败:

storageReference.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
    @Override
    public void onSuccess(Uri uri) {
        profileImage.setImageURI(uri);
        Log.d("Test"," Success!");
    }
}).addOnFailureListener(new OnFailureListener() {
    @Override
    public void onFailure(@NonNull Exception exception) {
        Log.d("Test"," Failed!");
    }
});

3 个答案:

答案 0 :(得分:0)

尝试获取已上传到数据库中的图像的下载URL,并使用Picasso或GLIDE库将其加载到所需的imageview中。

答案 1 :(得分:0)

您从Firebase存储中检索的uri可能有问题,请尝试将其记录在日志中,如下所示:

Log.d("uri:",uri.toString());

这可能会提示您,检索值出了什么问题。如果您选择使用GlidePicasso,请从上面的链接中引用其GitHub页面,并查看所需内容。

使用Glide和Picasso都很简单,这是一个如何使用Glide将图像存储在imageView中的示例。

   // Reference to an image file in Cloud Storage
StorageReference storageReference = = FirebaseStorage.getInstance().getReference().child("yourImageReferencePath");


ImageView image = (ImageView)findViewById(R.id.imageView);

// Load the image using Glide
Glide.with(this /* context */)
        .using(new FirebaseImageLoader())
        .load(storageReference)
        .into(image );

如果您不想使用任何外部库并想要检索图像,请执行refer this answer,可能会有所帮助。

答案 2 :(得分:0)

使用以下代码,您可以在ImageView上设置图像:

StorageReference storageReference = FirebaseStorage.getInstance().getReference();
StorageReference photoReference= storageReference.child("pictures/photo1.jpg");

                final long ONE_MEGABYTE = 1024 * 1024;
                photoReference.getBytes(ONE_MEGABYTE).addOnSuccessListener(new OnSuccessListener<byte[]>() {
                    @Override
                    public void onSuccess(byte[] bytes) {
                        Bitmap bmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
                        imageView.setImageBitmap(bmp);

                    }
                }).addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception exception) {
                        Toast.makeText(getApplicationContext(), "No Such file or Path found!!", Toast.LENGTH_LONG).show();
                    }
                });

您也可以使用Uri,因为您需要将字节数组保存到文件中。将以下代码用于同一代码:

File f = new File(Environment.getExternalStorageDirectory()
                        + File.separator + "test.jpg");
f.createNewFile();
//write the bytes in file
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());

// remember close de FileOutput
fo.close();