@@ -3,7 +3,9 @@ package com.neki.android.core.common.util
33import android.content.Context
44import android.graphics.Bitmap
55import android.graphics.BitmapFactory
6+ import android.graphics.Matrix
67import android.net.Uri
8+ import androidx.exifinterface.media.ExifInterface
79import kotlinx.coroutines.Dispatchers
810import kotlinx.coroutines.withContext
911import java.io.ByteArrayOutputStream
@@ -16,8 +18,22 @@ fun Uri.toByteArray(
1618 quality : Int = DEFAULT_QUALITY ,
1719 format : Bitmap .CompressFormat = Bitmap .CompressFormat .JPEG ,
1820): ByteArray? {
21+ val orientation = context.contentResolver.openInputStream(this )?.use { input ->
22+ ExifInterface (input).getAttributeInt(
23+ ExifInterface .TAG_ORIENTATION ,
24+ ExifInterface .ORIENTATION_UNDEFINED ,
25+ )
26+ } ? : ExifInterface .ORIENTATION_UNDEFINED
1927 val bytes = context.contentResolver.openInputStream(this )?.use { it.readBytes() } ? : return null
20- return bytes.compress(quality, format)
28+ val bitmap = BitmapFactory .decodeByteArray(bytes, 0 , bytes.size) ? : return null
29+ val rotatedBitmap = bitmap.applyOrientation(orientation)
30+
31+ return ByteArrayOutputStream ().use { outputStream ->
32+ rotatedBitmap.compress(format, quality, outputStream)
33+ if (rotatedBitmap != = bitmap) bitmap.recycle()
34+ rotatedBitmap.recycle()
35+ outputStream.toByteArray()
36+ }
2137}
2238
2339suspend fun String.urlToByteArray (
@@ -28,6 +44,29 @@ suspend fun String.urlToByteArray(
2844 bytes.compress(quality, format)
2945}
3046
47+ private fun Bitmap.applyOrientation (orientation : Int ): Bitmap {
48+ val matrix = Matrix ()
49+ when (orientation) {
50+ ExifInterface .ORIENTATION_ROTATE_90 -> matrix.postRotate(90f )
51+ ExifInterface .ORIENTATION_ROTATE_180 -> matrix.postRotate(180f )
52+ ExifInterface .ORIENTATION_ROTATE_270 -> matrix.postRotate(270f )
53+ ExifInterface .ORIENTATION_FLIP_HORIZONTAL -> matrix.postScale(- 1f , 1f )
54+ ExifInterface .ORIENTATION_FLIP_VERTICAL -> matrix.postScale(1f , - 1f )
55+ ExifInterface .ORIENTATION_TRANSPOSE -> {
56+ matrix.postRotate(90f )
57+ matrix.postScale(- 1f , 1f )
58+ }
59+
60+ ExifInterface .ORIENTATION_TRANSVERSE -> {
61+ matrix.postRotate(270f )
62+ matrix.postScale(- 1f , 1f )
63+ }
64+
65+ else -> return this
66+ }
67+ return Bitmap .createBitmap(this , 0 , 0 , width, height, matrix, true )
68+ }
69+
3170private fun ByteArray.compress (
3271 quality : Int ,
3372 format : Bitmap .CompressFormat ,
0 commit comments