E/BitmapFactory: Unable to decode stream: java.io.FileNotFoundException (No such file or directory)

后端 未结 1 681
萌比男神i
萌比男神i 2020-12-22 05:41

I want to decode the picture I took from the gallery but it has an error. I have tried various methods but none have been successful. Please help to fix my code.

Thi

1条回答
  •  时光说笑
    2020-12-22 06:11

    Select image from gallery fun like this:

        private fun selectImageFromGallery() {
    
        val intent = Intent()
        intent.type = "image/*"
        intent.action = Intent.ACTION_GET_CONTENT
        startActivityForResult(
            Intent.createChooser(
                intent,
                "Please select..."
            ),
            GALLERY_REQUEST_CODE
        )
    }
    

    onActivityResult like this:

     override fun onActivityResult(
        requestCode: Int,
        resultCode: Int,
        data: Intent?
    ) {
    
        super.onActivityResult(
            requestCode,
            resultCode,
            data
        )
    
        if (requestCode == GALLERY_REQUEST_CODE
            && resultCode == Activity.RESULT_OK
            && data != null
            && data.data != null
        ) {
    
            // Get the Uri of data
            val file_uri = data.data
            img_adu.setImageURI(file_uri)
            img_adu.visibility = View.VISIBLE
            bitmap = file_uri?.getCapturedImage(applicationContext)
            val stream = ByteArrayOutputStream()
                bitmap?.compress(Bitmap.CompressFormat.JPEG, 100, stream)
                bitmap?.recycle()
                val array = stream.toByteArray()
                encoded_string = Base64.encodeToString(array, 0)
        }
     }
    

    Get bitmap extension like this:

    fun Uri.getCapturedImage(context: Context): Bitmap? {
    
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
        val source =
            context?.contentResolver?.let { ImageDecoder.createSource(it, this) }
        return source?.let { ImageDecoder.decodeBitmap(it) }
    } else {
        return MediaStore.Images.Media.getBitmap(
            context?.contentResolver,
            this
        )
      }
    }
    

    Good luck

    0 讨论(0)
提交回复
热议问题