【问题标题】:How to upload image captured from camera to firebase storage?如何将从相机捕获的图像上传到 Firebase 存储?
【发布时间】:2019-10-03 17:33:10
【问题描述】:

我想将从相机捕获的图像上传到 Firebase 存储。一旦获得图像的 Uri 格式,我就知道如何存储图像,但是我从相机活动中获取位图。所以我需要知道该怎么做?

click_picture.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                startActivityForResult(intent,2);
            }
        });

 @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Bitmap bitmap = (Bitmap)data.getExtras().get("data");
        image.setImageBitmap(bitmap);
    }
public String getFileExtendsion(Uri uri){
        ContentResolver contentResolver = getActivity().getContentResolver();
        MimeTypeMap mime = MimeTypeMap.getSingleton();
        return  mime.getExtensionFromMimeType(contentResolver.getType(uri));
    }
public void uploadFile(){
        if(mImageUri!=null){
            final StorageReference fileReference = mStorageRef.child("ProfilePicture"+"."+getFileExtendsion(mImageUri));
            fileReference.putFile(mImageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                @Override
                public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                    fileReference.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                        @Override
                        public void onSuccess(Uri uri) {
                            ///store the uri
                        }
                    });
                }
            }).addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    Log.i("Fail",e.getMessage());
                }
            });
        }
    }

我有函数 uploadFile() 将图像的 Uri 存储到 firebase 存储,然后获取图像的 url 以将其存储在 firebase 实时数据库中。但是我需要将位图转换为 Uri 吗?如果是,如何?我找到的代码不起作用,如果还有其他方法,请告诉我!
感谢您的宝贵时间 :)

【问题讨论】:

    标签: android firebase firebase-storage


    【解决方案1】:

    如果您要从摄像头获取位图,请参阅 Firebase 文档中的第一个示例,该示例展示了 upload from data that you have in memory 的用法,它以 Bitmap 开头很方便。

    从那里:

    // Get the data from an ImageView as bytes
    imageView.setDrawingCacheEnabled(true);
    imageView.buildDrawingCache();
    Bitmap bitmap = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
    byte[] data = baos.toByteArray();
    
    UploadTask uploadTask = mountainsRef.putBytes(data);
    

    【讨论】:

    • 好的,谢谢!但是该示例在将 Uri 文件保存在设备上后将其保存到特定路径,但我不想将其存储在设备上。我该怎么办?
    猜你喜欢
    • 2021-08-20
    • 2018-06-05
    • 1970-01-01
    • 2018-01-13
    • 1970-01-01
    • 2018-03-14
    • 1970-01-01
    • 2016-12-03
    • 2021-08-30
    相关资源
    最近更新 更多