1
Fork 0
mirror of https://github.com/Steffo99/twom.git synced 2024-11-21 23:54:26 +00:00

Fix image picker

This commit is contained in:
Steffo 2023-12-02 02:39:45 +01:00
parent 19d01e2c40
commit d262ae8cf7
Signed by: steffo
GPG key ID: 2A24051445686895

View file

@ -1,6 +1,9 @@
package eu.steffo.twom.create
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Matrix
import android.media.ExifInterface
import android.net.Uri
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.PickVisualMediaRequest
@ -54,10 +57,75 @@ fun CreateActivityContent(
if (it == null) {
avatarBitmap = null
} else {
val stream = context.contentResolver.openInputStream(it)
if (stream != null) {
avatarBitmap = BitmapFactory.decodeStream(stream).asImageBitmap()
stream.close()
// Open two streams...
// One to read the EXIF metadata from:
val exifStream = context.contentResolver.openInputStream(it)
// One to read the image data itself from:
val bitmapStream = context.contentResolver.openInputStream(it)
if (exifStream != null && bitmapStream != null) {
// Use the EXIF metadata to determine the orientation of the image
val exifInterface = ExifInterface(exifStream)
val orientation =
exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, 1)
exifStream.close()
// Parse the image data as-is
val originalBitmap = BitmapFactory.decodeStream(bitmapStream)
bitmapStream.close()
// Determine the starting points and the size to crop the image to a 1:1 square
val xStart: Int
val yStart: Int
val size: Int
if (originalBitmap.width > originalBitmap.height) {
yStart = 0
xStart = (originalBitmap.width - originalBitmap.height) / 2
size = originalBitmap.height
} else {
xStart = 0
yStart = (originalBitmap.height - originalBitmap.width) / 2
size = originalBitmap.width
}
// Create a transformation matrix to rotate the bitmap based on the orientation
val transformationMatrix: Matrix = Matrix()
// TODO: Make sure these transformations are valid
when (orientation) {
ExifInterface.ORIENTATION_FLIP_HORIZONTAL -> transformationMatrix.postScale(
-1f,
1f
)
ExifInterface.ORIENTATION_ROTATE_180 -> transformationMatrix.postRotate(180f)
ExifInterface.ORIENTATION_FLIP_VERTICAL -> transformationMatrix.postScale(
1f,
-1f
)
ExifInterface.ORIENTATION_TRANSPOSE -> {/* TODO: Transpose the image Matrix */
}
ExifInterface.ORIENTATION_ROTATE_90 -> transformationMatrix.postRotate(90f)
ExifInterface.ORIENTATION_TRANSVERSE -> {/* TODO: Flip horizontally the image Matrix, then transpose it */
}
ExifInterface.ORIENTATION_ROTATE_270 -> transformationMatrix.postRotate(270f)
}
// Crop the bitmap
val croppedBitmap = Bitmap.createBitmap(
originalBitmap,
xStart,
yStart,
size,
size,
transformationMatrix,
true
)
avatarBitmap = croppedBitmap.asImageBitmap()
}
}
}