what I want to do is to take a photo with the cellphone en then displays that image in a imageview, but when I did that the image appeared roated 90 degrees. So I searched for solutions to that issue and found that I had to do it this way.
private fun capturePhoto() {
val cameraIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
val filePhoto = File(Environment.getExternalStorageDirectory(), "Pic.jpg")
imageUri = FileProvider.getUriForFile(
this@ShowLocationFragment.requireActivity(),
"com.example.countriesapp.provider",
filePhoto
)
path = imageUri.path
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri)
startActivityForResult(cameraIntent, REQUEST_CODE)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (resultCode == Activity.RESULT_OK && requestCode == REQUEST_CODE) {
if (path != null) {
val inputStream =
this@ShowLocationFragment.requireActivity().contentResolver.openInputStream(
imageUri
)
val ei = inputStream?.let { ExifInterface(it) }
val orientation = ei?.getAttributeInt(
ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_UNDEFINED
)
val bitmap = getBitmapFromUri()
var rotatedBitmap: Bitmap? = null
rotatedBitmap = when (orientation) {
ExifInterface.ORIENTATION_ROTATE_90 -> rotateImage(bitmap, 90)
ExifInterface.ORIENTATION_ROTATE_180 -> rotateImage(bitmap, 180)
ExifInterface.ORIENTATION_ROTATE_270 -> rotateImage(bitmap, 270)
else -> bitmap
}
binding.ivPlaceMemory.setImageBitmap(rotatedBitmap)
}
}
}
These are rotateImage and getBitmapFromUri functions
private fun rotateImage(source: Bitmap?, angle: Int): Bitmap? {
if (source == null) return null
val matrix = Matrix()
matrix.postRotate(angle.toFloat())
return Bitmap.createBitmap(
source, 0, 0, source.width, source.height,
matrix, true
)
}
private fun getBitmapFromUri(): Bitmap? {
this@ShowLocationFragment.requireActivity().contentResolver.notifyChange(imageUri, null)
val cr: ContentResolver = this@ShowLocationFragment.requireActivity().contentResolver
val bitmap: Bitmap
return try {
bitmap = MediaStore.Images.Media.getBitmap(cr, imageUri)
bitmap
} catch (e: Exception) {
e.printStackTrace()
null
}
}
However, I'm having this exception java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1331636152, result=-1, data=null} to activity {com.example.countriesapp/com.example.countriesapp.presentation.MainActivity}: java.io.FileNotFoundException: open failed: ENOENT (No such file or directory)
Can anybody help to figure out what is going on?
Ive tried to search for solutions but havent found anything that works out.