从相机捕获图像并存储在 Firebase 实时数据库中

Capture Image from camera and store in Firebase RealTime DataBase

我正在用 Kotlin 为朋友的 crystal 样本创建库存应用程序。预期逻辑是:

但是,我不确定如何将图像存储在 Firebase 实时数据库中。我在 Java 中看到了这个过程的例子,它要求在 onActivityResult 中,data.data 在存储之前转换为位图,但我不完全理解转换它。我希望有人可以解释将图像 从相机 而不是从相机 存储到 firebase 中的方法和原因。

我的代码在下面,我添加一些问题。

RockEnry.kt

package com.inven.rock_stock

import android.content.Intent
import android.graphics.Picture
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.database.core.Context

class RockEntry {
    var name = ""
    var purchDate = ""
    var local = ""
    var mine = ""
    var weight = ""
    var paid = ""
    var asking = ""
    var description = ""
    var dimensions = ""

    constructor(name:String,purchDate:String,local:String,mine:String,
                weight:String,paid:String,asking:String,description:String,dimensions:String,){
        this.name = name
        this.purchDate = purchDate
        this.local = local
        this.mine = mine
        this.weight = weight
        this.paid = paid
        this.asking = asking
        this.description = description
        this.dimensions = dimensions

如何在构造函数中存储图片?

MainActivity

package com.inven.rock_stock

import android.app.Activity
import android.content.ActivityNotFoundException
import android.content.Intent
import android.os.Bundle
import android.provider.MediaStore
import androidx.appcompat.app.AppCompatActivity
import com.google.firebase.database.FirebaseDatabase
import kotlinx.android.synthetic.main.activity_main.*

var CAMERA_REQUEST_CODE = 0
var database = FirebaseDatabase.getInstance().reference

class MainActivity : AppCompatActivity() {  
    private val TAG = "MyActivity"
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)


        button.setOnClickListener {
            var name = name.text.toString()
            var local = locality.text.toString()
            var mine = mine.text.toString()
            var weight = weight.text.toString()
            var dimensions = dimensions.text.toString()
            var paid = paid.text.toString()
            var asking = asking.text.toString()
            var description = description.text.toString()

            database.child("Rocks").child(name.toLowerCase()).setValue(
                RockEntry(
                    name,
                    local,
                    mine,
                    weight,
                    dimensions
                    paid,
                    asking,
                    description


                )
            )
        }

        imageBtn.setOnClickListener {
            takePicture()
        }
    }


    private fun takePicture() {
        CAMERA_REQUEST_CODE = 222
        val takePictureIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
        try {
            startActivityForResult(takePictureIntent, CAMERA_REQUEST_CODE)
        } catch (e: ActivityNotFoundException) {
            // display error state to the user
        }
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        when (requestCode) {
            CAMERA_REQUEST_CODE -> {
                if (resultCode == Activity.RESULT_OK && data != null) {

println(“我需要做什么才能将图片导入 firebase?”)

                    val singularity = data.data

                    }

                }

            }

        }

    }

我想我在以下方面遇到了一些概念性问题:

我在 Java , (which I probably should have created this project in) but my conversion is pretty ugly at this point.
here's the doc i've been staring at photobasicsDoc, uploadDoc

中找到了一些示例

我的误解是 FireBaseDatabase 和 FireBaseStorage 是同一个。

  • 我最重要的是使用 firebase 配置了一些存储 Android Studio 中的工具(还添加了适当的依赖项)
    我声明了 private var mStorageRef: StorageReference? = null 并将其设置为等于
    mStorageRef = FirebaseStorage.getInstance().getReference("Images") onCreate.

    以下是我的代码中遗漏的代码 onActivityResult:

    val imageBitmap = data.extras?.get("data") as Bitmap
                        val baos = ByteArrayOutputStream()
                        imageBitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos)
                        val datar = baos.toByteArray()
    
                        storageRef!!.putBytes(datar)
    

我仍然欢迎对 post 提出意见,仍然有效的问题:

  • 我应该如何 link FireBaseDataBase 和 FireBaseStorage。
    更新: 您可以 'link' FireBaseDataBase 和 FireBaseStorage 文件通过存储文件在数据库中的位置或获取 http 下载 link 到文件并将其存储在数据库中。

     storageRef.downloadUrl?.addOnSuccessListener { 
          downloadUri -> {
          //do something with https download file link
          var link = downloadUri.toString()
          //which is different from 
          var databaseStoragelocation = storageref.toString()
          }
      }
    
  • 你应该如何在对象中存储图片。
    更新:您可以创建一个将 ByteArray 或 Uri 作为参数的构造函数

  • 照片从图库中返回的方式与 从实时相机返回照片的方式?
    更新: 基本上 takePicture 和 pickImageFromGallery() (下)都 运行 在 Intent 下(下面的代码示例)。在 onActivityResult 中,相机图片将显示为位图,图库图片将显示为 Uri

         // take picture from camera
         private fun takePicture() {
         CAMERA_REQUEST_CODE = 222
         val takePictureIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
         try {
             startActivityForResult(takePictureIntent, CAMERA_REQUEST_CODE)
         } catch (e: ActivityNotFoundException) {
             // display error state to the user
         }
     }
    
     /* goes to gallery to select image */
     private fun pickImageFromGallery() {
         val intent = Intent()
         intent.type = "image/*"
         intent.action = Intent.ACTION_GET_CONTENT
    
         startActivityForResult(intent, GALLERY_REQUEST_CODE)
    
    
     }
    
     /* checks to see if app had permission to access gallery, then calls pickImageFromGallery */
     private fun checkPermissionForImage() {
         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
             if ((checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED)
                 && (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED)
             ) {
                 val permission = arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE)
                 val permissionCoarse = arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE)
    
                 val PERMISSION_CODE_READ = 0
                 requestPermissions(
                     permission,
                     PERMISSION_CODE_READ
                 ) // GIVE AN INTEGER VALUE FOR PERMISSION_CODE_READ LIKE 1001
                 val PERMISSION_CODE_WRITE = 0
                 requestPermissions(
                     permissionCoarse,
                     PERMISSION_CODE_WRITE
                 ) // GIVE AN INTEGER VALUE FOR PERMISSION_CODE_WRITE LIKE 1002
             } else {
                 pickImageFromGallery()
             }
         }
     }
    
          /* on completion of pickImageFromGallery or takePicture this 
            function will store the image in the appropriate array to be 
            later uploaded */
     override fun onActivityResult(requestCode: Int, resultCode: Int, 
     data: Intent?) {
         val filePath: Uri?
         /* reference to storagebase for photos */
    
         super.onActivityResult(requestCode, resultCode, data)
         when (requestCode) {
    
             CAMERA_REQUEST_CODE -> {
                 if (resultCode == Activity.RESULT_OK && data != null) {
                     val imageBitmap = data.extras?.get("data") as 
                     Bitmap)
                     val baos = ByteArrayOutputStream()
                     imageBitmap.compress(Bitmap.CompressFormat.JPEG, 
                     100, baos)
                     val datar = baos.toByteArray() // <- the picture is 
                                                    ready to upload here
                     // adding photo bytearray to a array
                     campics.add(datar)                                                      
                 }
             }
    
             GALLERY_REQUEST_CODE -> {
                 if (resultCode == Activity.RESULT_OK && data != null) {
                     filePath = data.data
                     val imageBitmap = 
                     MediaStore.Images.Media.getBitmap(contentResolver, 
                     filePath)
                     // adding gallery pic Uri to array
                     filePath?.let { galpics.add(it) } 
    
                 }
             }
         }
     }