package com.barcodescanner import android.graphics.Bitmap import android.graphics.BitmapFactory import android.util.Log import java.io.File import java.io.InputStream import kotlin.math.abs import kotlin.math.floor import kotlin.math.ln import kotlin.math.pow class BitmapUtils { companion object{ fun getBitmap(filePath: String?): Bitmap? { val options = BitmapFactory.Options() options.inJustDecodeBounds = true BitmapFactory.decodeFile(filePath, options) val scaleByHeight: Boolean = abs(options.outHeight - 100) >= abs(options.outWidth - 100) if (options.outHeight * options.outWidth * 2 >= 16384) { val sampleSize: Double = if (scaleByHeight) options.outHeight *1.0 / 100 else options.outWidth * 1.0 / 100 options.inSampleSize = 2.0.pow( floor( ln(sampleSize) / ln(2.0) ) ).toInt() } options.inJustDecodeBounds = false options.inTempStorage = ByteArray(512) return BitmapFactory.decodeFile(filePath, options) } fun getResizedBitmap(filePath: String?, maxWidth: Int, maxHeight: Int): Bitmap? { return filePath?.let { // First, determine the dimensions of the original image val options = BitmapFactory.Options() options.inJustDecodeBounds = true BitmapFactory.decodeFile(filePath, options) // Calculate the sample size to fit within the desired dimensions while maintaining aspect ratio options.inSampleSize = calculateInSampleSize(options, maxWidth, maxHeight) // Decode the image with the calculated sample size options.inJustDecodeBounds = false options.inPreferredConfig = Bitmap.Config.ARGB_8888 BitmapFactory.decodeFile(filePath, options) } } private fun calculateInSampleSize(options: BitmapFactory.Options, maxWidth: Int, maxHeight: Int): Int { val originalWidth = options.outWidth val originalHeight = options.outHeight var inSampleSize = 1 if (originalWidth > maxWidth || originalHeight > maxHeight) { val widthRatio = Math.round(originalWidth.toFloat() / maxWidth.toFloat()) val heightRatio = Math.round(originalHeight.toFloat() / maxHeight.toFloat()) inSampleSize = if (widthRatio < heightRatio) widthRatio else heightRatio } return inSampleSize } } }