Просмотр исходного кода

feat(helper): 添加位图解码辅助类

- 实现了采样位图解码功能,支持指定宽高要求
- 添加了计算采样大小的算法,优化内存使用
- 设置位图配置为RGB_565以减少内存占用
- 包含边界检查防止无效参数导致异常
- 提供了高效的图片加载解决方案
徐勤民 2 дней назад
Родитель
Сommit
88ff873959
1 измененных файлов с 41 добавлено и 0 удалено
  1. 41 0
      app/src/main/java/com/nova/brain/glass/helper/BitmapDecodeHelper.kt

+ 41 - 0
app/src/main/java/com/nova/brain/glass/helper/BitmapDecodeHelper.kt

@@ -0,0 +1,41 @@
+package com.nova.brain.glass.helper
+
+import android.graphics.Bitmap
+import android.graphics.BitmapFactory
+import kotlin.math.max
+
+object BitmapDecodeHelper {
+    fun decodeSampledBitmap(path: String, reqWidth: Int, reqHeight: Int): Bitmap? {
+        val boundsOptions = BitmapFactory.Options().apply {
+            inJustDecodeBounds = true
+        }
+        BitmapFactory.decodeFile(path, boundsOptions)
+
+        val decodeOptions = BitmapFactory.Options().apply {
+            inSampleSize = calculateInSampleSize(boundsOptions, reqWidth, reqHeight)
+            inPreferredConfig = Bitmap.Config.RGB_565
+        }
+        return BitmapFactory.decodeFile(path, decodeOptions)
+    }
+
+    private fun calculateInSampleSize(
+        options: BitmapFactory.Options,
+        reqWidth: Int,
+        reqHeight: Int
+    ): Int {
+        val height = options.outHeight
+        val width = options.outWidth
+        if (height <= 0 || width <= 0 || reqWidth <= 0 || reqHeight <= 0) {
+            return 1
+        }
+        var inSampleSize = 1
+        if (height > reqHeight || width > reqWidth) {
+            val halfHeight = height / 2
+            val halfWidth = width / 2
+            while (halfHeight / inSampleSize >= reqHeight && halfWidth / inSampleSize >= reqWidth) {
+                inSampleSize *= 2
+            }
+        }
+        return max(1, inSampleSize)
+    }
+}