60 lines
2.2 KiB
Kotlin
60 lines
2.2 KiB
Kotlin
package core.utils
|
|
|
|
import android.content.Context
|
|
import android.graphics.Bitmap
|
|
import android.graphics.BitmapFactory
|
|
import android.graphics.Matrix
|
|
import android.net.Uri
|
|
import java.io.File
|
|
import java.io.FileOutputStream
|
|
import java.util.UUID
|
|
|
|
object ImageUtils {
|
|
fun compressImage(context: Context, uri: Uri, maxWidth: Int = 1280, maxHeight: Int = 1280, quality: Int = 80): File? {
|
|
return try {
|
|
val inputStream = context.contentResolver.openInputStream(uri)
|
|
val options = BitmapFactory.Options().apply {
|
|
inJustDecodeBounds = true
|
|
}
|
|
BitmapFactory.decodeStream(inputStream, null, options)
|
|
inputStream?.close()
|
|
|
|
var inSampleSize = 1
|
|
if (options.outHeight > maxHeight || options.outWidth > maxWidth) {
|
|
val halfHeight = options.outHeight / 2
|
|
val halfWidth = options.outWidth / 2
|
|
while (halfHeight / inSampleSize >= maxHeight && halfWidth / inSampleSize >= maxWidth) {
|
|
inSampleSize *= 2
|
|
}
|
|
}
|
|
|
|
val decodeOptions = BitmapFactory.Options().apply {
|
|
inSampleSize = inSampleSize
|
|
}
|
|
val finalInputStream = context.contentResolver.openInputStream(uri)
|
|
var bitmap = BitmapFactory.decodeStream(finalInputStream, null, decodeOptions)
|
|
finalInputStream?.close()
|
|
|
|
if (bitmap == null) return null
|
|
|
|
// Resize if still too large
|
|
if (bitmap.width > maxWidth || bitmap.height > maxHeight) {
|
|
val scale = Math.min(maxWidth.toFloat() / bitmap.width, maxHeight.toFloat() / bitmap.height)
|
|
val matrix = Matrix().apply { postScale(scale, scale) }
|
|
bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.width, bitmap.height, matrix, true)
|
|
}
|
|
|
|
val file = File(context.cacheDir, "compressed_${UUID.randomUUID()}.jpg")
|
|
val out = FileOutputStream(file)
|
|
bitmap.compress(Bitmap.CompressFormat.JPEG, quality, out)
|
|
out.flush()
|
|
out.close()
|
|
|
|
file
|
|
} catch (e: Exception) {
|
|
e.printStackTrace()
|
|
null
|
|
}
|
|
}
|
|
}
|