如何从Firebase存储中设置图像视图? [英] How to set image view from Firebase storage?
问题描述
我从文档和在线帮助中都尝试了所有示例,但是我无法获得存储中要显示在图像视图上的简单图像.
I tried all examples both from the docs and from online help, but I can't get a simple image I have in the storage to display on an image view.
假设我的图片存储在名为picture的文件夹中,因此photo1.jpg存储在引用中:
assuming I have pictures in the storage in a folder called pictures so photo1.jpg is stored in the reference:
StorageReference storageReference = FirebaseStorage.getInstance().getReference();
StorageReference photoReference= storageReference.child("pictures/photo1.jpg");
但是如何设置它,并将其内容替换为我通过id找到的现有图像视图:
But how do I set it and replace the contents with an existing image view that I find by id:
ImageView photoView= (ImageView) findViewById(R.id.photo_view);
在获取Uri的监听器上,我一直失败:
I keep getting failure on the listener to get 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!");
}
});
推荐答案
使用以下代码可以在ImageView上设置图像:
Using below code you can set image on 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,因为您需要将字节数组保存到文件中.将以下代码用于同一代码:
You can use the Uri as well, for that you need to save the byte array to a file. Use below code for the same:
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();
这篇关于如何从Firebase存储中设置图像视图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!