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
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