是用户上传图片还是您通过应用上传?
如果是这样,我可以建议:
有一个私人图像按钮。
在 onCreate() 中
imageButton = (ImageButton) findViewById(R.id.ibImageSelect);
imageButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent, Gallery_Request);
}
});
在方法体之外:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == Gallery_Request && resultCode == RESULT_OK) {
imageUri = data.getData();
imageButton.setImageURI(imageUri);
}
}
点击按钮
StorageReference upload = storageReference.child("what you want");
Bitmap bmp = MediaStore.Images.Media.getBitmap(getContentResolver(), imageUri);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] data = baos.toByteArray();
UploadTask filePath = upload.child(imageUri.getLastPathSegment()).putBytes(data);
filePath.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
filePath.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
DatabaseReference newPost = mref.push(); //this generates a random unique key
replace with your own if you want, since you already got your own structure
newPost.child("image").setValue(imageUri.getLastPathSegment());
//set image name so can use this to download the image
}
});
您可以在数据的每个节点中有一个“状态”子节点,然后在下载图像时遍历所有节点,检查状态是否是您想要的状态。然后获取图片下载密钥。
用于下载图片:
遍历节点和子节点,获取img url,
String ref = "image folder in firebase storage/" + imgurl;
storageRef.child(ref).getBytes(Long.MAX_VALUE).addOnSuccessListener(new OnSuccessListener<byte[]>() {
@Override
public void onSuccess(byte[] bytes) {
// Use the bytes to display the image
final Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
ImageView iv = (ImageView) findViewByID(R.id...);
iv.setImageBitmap(bitmap);
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception exception) {
Log.i("error", exception.getMessage());
}
});