How to get a Uri object from Bitmap

后端 未结 7 1625
醉话见心
醉话见心 2020-12-09 15:55

On a certain tap event, I ask the user to add an image. So I provide two options:

  1. To add from gallery.
  2. To click a new image from camera.
7条回答
  •  不思量自难忘°
    2020-12-09 16:46

    if you get image from camera there is no way to get Uri from a bitmap, so you should save your bitmap first.

    launch camera intent

    startActivityForResult(Intent(MediaStore.ACTION_IMAGE_CAPTURE), 8)
    

    then, override

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    
        if (resultCode == Activity.RESULT_OK && requestCode == 8) {
            val bitmap = data?.extras?.get("data") as Bitmap
    
            val uri = readWriteImage(bitmap)
        }
    }
    

    also create method to store bitmap and then return the Uri

    fun readWriteImage(bitmap: Bitmap): Uri {
        // store in DCIM/Camera directory
        val dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM)
        val cameraDir = File(dir, "Camera/")
    
        val file = if (cameraDir.exists()) {
            File(cameraDir, "LK_${System.currentTimeMillis()}.png")
        } else {
            cameraDir.mkdir()
            File(cameraDir, "LK_${System.currentTimeMillis()}.png")
        }
    
        val fos = FileOutputStream(file)
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos)
        fos.flush()
        fos.close()
    
        Uri.fromFile(file)
    }
    

    PS: dont forget to Add Permission and handle runtime permission (API >= 23)

提交回复
热议问题