当前位置: 首页 > 知识库问答 >
问题:

如何从摄像头捕获图像并上传到Firebase

沃念
2023-03-14

我正在尝试用相机拍照并上传到Firebase。我使用AlertDialog询问用户是否想要使用相机或从图库中选择图像。我可以用相机拍照,但是当我试图上传图像时,它说找不到图像。

以下是我的图像选择方法:

    private void imageSelect(Context context) {
    final CharSequence[] options = { "Take Photo", "Choose from Gallery","Cancel" };

    AlertDialog.Builder builder = new AlertDialog.Builder(context);
    builder.setTitle("Choose Image");

    builder.setItems(options, new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int item) {

            if (options[item].equals("Take Photo")) {
                Intent takePicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                startActivityForResult(takePicture, 0);

            } else if (options[item].equals("Choose from Gallery")) {
                Intent pickPhoto = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(pickPhoto , 1);

            } else if (options[item].equals("Cancel")) {
                dialog.dismiss();
            }
        }
    });
    builder.show();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    switch(requestCode) {
        case 0:
            if(resultCode == RESULT_OK){
                filePath = data.getData();
            }

            break;
        case 1:
            if(resultCode == RESULT_OK){
                filePath = data.getData();
                try {
                    Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
            }
            break;
    }
}

下面是我上传图片的方法

    private void uploadImage() {
    if (filePath != null) {
        //Code for showing progressDialog while uploading
        ProgressDialog progressDialog = new ProgressDialog(this);
        progressDialog.setTitle("Uploading...");
        progressDialog.show();

        StorageReference ref = storageReference.child("images/" + name);
        //Adding listeners on upload or failure of image
        ref.putFile(filePath).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                //Image uploaded successfully
                progressDialog.dismiss();
                Toast.makeText(add_property.this, "Image Uploaded!", Toast.LENGTH_SHORT).show();
            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                //Error, Image not uploaded
                progressDialog.dismiss();
                Toast.makeText(add_property.this, "Failed " + e.getMessage(), Toast.LENGTH_SHORT).show();
            }
        }).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
            //Progress Listener for loading
            @Override
            public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
                double progress = (100.0 * taskSnapshot.getBytesTransferred() / taskSnapshot.getTotalByteCount());
                progressDialog.setMessage("Uploaded " + (int) progress + "%");
            }
        });
    }
    else {
        Toast.makeText(getApplicationContext(),"No image found",Toast.LENGTH_SHORT).show();
    }
}

提前感谢任何帮助的朋友。

共有2个答案

祁高格
2023-03-14

一个潜在的解决方法是将字节数组上传到firebase中;因此,当使用相机拍摄照片时,您可以从在onActivityResult()中接收到的意图中获取位图字节数组,并最终使用ref.putBytes()方法将字节数组上载到firebase存储。

这可以通过以下几个步骤完成:

在这里,我假设onActivityResult()中相机的请求代码为1:

final int FROM_GALLERY = 0;
final int FROM_CAMERA = 1;

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    
    if (resultCode == RESULT_OK && data != null) {

        switch (requestCode) {
        
            case FROM_GALLERY:
            
                // Handle image from the gallery
                filePath = data.getData();
                break;


            case FROM_CAMERA:
            
                // Handle image from the camera

                if (data.getExtras() != null) {
                    Bitmap photoBitmap = (Bitmap) data.getExtras().get("data");
                    byte[] bitmapBytes = getBytesFromBitmap(bitmap, 100);
                    uploadToFirebase(bitmapBytes);
                    
                }

                break;
        }

    }
}


// convert from bitmap to byte array
public static byte[] getBytesFromBitmap(Bitmap bitmap, int quality) {
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG, quality, stream);
    // bitmap.compress(Bitmap.CompressFormat.PNG, quality, stream); // According to the needed quality
    return stream.toByteArray();
}   



public void uploadToFirebase(bytes[] bytes) {
    StorageReference ref = .... 
    ref.putBytes(bytes)
        .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {

            }

        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception exception) {
            }

        }).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {

            }
        }); 
}
能逸清
2023-03-14

这是我的代码,我用我的应用程序和工作正常,尝试它,如果它的作品,然后恭喜

 public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_upload, container, false);
        requireActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        Button chooseImageButton = view.findViewById(R.id.upload_image_button);
        Button uploadImageButton = view.findViewById(R.id.done_button);
        uploadImageView = view.findViewById(R.id.upload_image_view);
        storageReference = FirebaseStorage.getInstance().getReference("uploads");
        databaseReference = FirebaseDatabase.getInstance().getReference("uploads");
        chooseImageButton.setOnClickListener(v -> openFileChooser());
        uploadImageButton.setOnClickListener(v -> {
            if (mUploadTask != null && mUploadTask.isInProgress()) {
                Toast.makeText(getActivity(), "Upload in Progress", Toast.LENGTH_SHORT).show();

            } else {
                uploadToFirebase(mImageUri);
            }


        });

        return view;
    }


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

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK
                && data != null && data.getData() != null) {
            mImageUri = data.getData();
            Picasso.get().load(mImageUri).into(uploadImageView);

        }
    }

    private String getFileExtension(Uri uri) {

        ContentResolver contentResolver = requireActivity().getContentResolver();
        MimeTypeMap mime = MimeTypeMap.getSingleton();
        return mime.getExtensionFromMimeType(contentResolver.getType(uri));
    }

    private void uploadToFirebase(Uri mImageUri) {
        if (mImageUri != null) {
            final ProgressDialog progressDialog = new ProgressDialog(getActivity());
            progressDialog.setTitle("Uploading...");
            progressDialog.show();

            StorageReference reference = storageReference.child(System.currentTimeMillis()
                    + "." + getFileExtension(mImageUri));
            reference.putFile(mImageUri)
                    .addOnSuccessListener(taskSnapshot -> {
                        progressDialog.dismiss();
                        Toast.makeText(getActivity(), "Saved Succesfully", Toast.LENGTH_SHORT).show();
                        reference.getDownloadUrl()
                                .addOnSuccessListener(uri -> {
                                    Upload upload = new Upload(uri.toString());
                                    String uploadId = databaseReference.push().getKey();
                                    databaseReference.child(uploadId).setValue(upload);
                                });
                    })
                    .addOnProgressListener(snapshot -> {
                        double progress = (100.0 * snapshot.getBytesTransferred() / snapshot
                                .getTotalByteCount());
                        progressDialog.setMessage("Uploaded " + (int) progress + "%");
                    })
                    .addOnFailureListener(e -> {
                        progressDialog.dismiss();
                        Toast.makeText(getActivity(), "Error Ocurred" + e.getMessage(), Toast.LENGTH_SHORT).show();
                    });


        }
    }
} 
 类似资料:
  • 我正在开发一个简单的博客应用程序,允许用户将照片从手机图库和描述上传到Firebase服务器。我正在尝试修改我的当前项目,以允许用户从照相机捕获照片并将其上载到firebase服务器。 目前,我能够将我捕获的图像显示到Image按钮中,但是我无法将我的图像发布到Firebase服务器(提交发布按钮不会对我的点击功能做出反应)。 我怀疑我的startPosting()函数中有错误,或者我没有正确编码

  • 我有一个问题与我的代码,我必须上传图像到Firebase存储,我需要的图像来自画廊和相机,从画廊的图像是好的,但来自相机的图像给问题,图像加载在ImageView和被发送到数据库是黑色的。有人知道如何解决这个问题吗,或者你知道任何其他加载图像的方法吗? 来自画廊 从相机

  • 问题内容: 如何连续从摄像头捕获图像? 我想尝试对象识别(也许使用Java Media Framework)。 我当时正在考虑创建两个线程 一个线程: 节点1:捕获实时图像 节点2:将图片另存为“ 1.jpg” 节点3:等待5秒 节点4:重复… 其他线程: 节点1:等到捕获图像 节点2:使用“ 1.jpg”获取每个像素的颜色 节点3:将数据保存在数组中 节点4:重复… 问题答案: 此JavaCV实

  • 我正在尝试使用GStreamer将RTMP/RTSP流连接到v4l2loopback虚拟设备。 工程1-RTMP至AutoVideoSink,sudo gst-launch-1.0 rtspsrc位置=rtsp://192.168.xxx.xxx/live/av0 ! decodebin!自动视频接收器sudo gst-launch-1.0 rtmpsrc位置=rtmp://192.168.xxx

  • 我在我的屏幕上有四个图像视图,从相机中捕获图像并显示在其中,现在我想将这些图像上传到服务器上。因此,我使用了下面的代码来获取它们的路径,但它通过了异常。是否有可能从摄像机拍摄的图像视图将图像上传到服务器(无需将图像存储到内存中)。

  • 我有一个按钮,它向用户提供选择,他是否想要从画廊或相机的图像。当用户从图库拍摄图像时,我能够成功地将图像上传到Firebase存储,但是当用户选择相机时,我无法将图像上传到存储。这是用户选择相机时的onActivityResult代码 它将图像上传到我的imageview,但给我错误提示 当我尝试上载到存储时 我在stack overflow上遇到了一个类似的问题。 我认为公认的答案是错误的,因为