BitmapDecodeHelper.kt 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. package com.nova.brain.glass.helper
  2. import android.graphics.Bitmap
  3. import android.graphics.BitmapFactory
  4. import kotlin.math.max
  5. object BitmapDecodeHelper {
  6. fun decodeSampledBitmap(path: String, reqWidth: Int, reqHeight: Int): Bitmap? {
  7. val boundsOptions = BitmapFactory.Options().apply {
  8. inJustDecodeBounds = true
  9. }
  10. BitmapFactory.decodeFile(path, boundsOptions)
  11. val decodeOptions = BitmapFactory.Options().apply {
  12. inSampleSize = calculateInSampleSize(boundsOptions, reqWidth, reqHeight)
  13. inPreferredConfig = Bitmap.Config.RGB_565
  14. }
  15. return BitmapFactory.decodeFile(path, decodeOptions)
  16. }
  17. private fun calculateInSampleSize(
  18. options: BitmapFactory.Options,
  19. reqWidth: Int,
  20. reqHeight: Int
  21. ): Int {
  22. val height = options.outHeight
  23. val width = options.outWidth
  24. if (height <= 0 || width <= 0 || reqWidth <= 0 || reqHeight <= 0) {
  25. return 1
  26. }
  27. var inSampleSize = 1
  28. if (height > reqHeight || width > reqWidth) {
  29. val halfHeight = height / 2
  30. val halfWidth = width / 2
  31. while (halfHeight / inSampleSize >= reqHeight && halfWidth / inSampleSize >= reqWidth) {
  32. inSampleSize *= 2
  33. }
  34. }
  35. return max(1, inSampleSize)
  36. }
  37. }