From 88ff873959f7908c9b651e84a18eeba4c2510148 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BE=90=E5=8B=A4=E6=B0=91?= Date: Tue, 14 Apr 2026 23:00:45 +0800 Subject: [PATCH] =?UTF-8?q?feat(helper):=20=E6=B7=BB=E5=8A=A0=E4=BD=8D?= =?UTF-8?q?=E5=9B=BE=E8=A7=A3=E7=A0=81=E8=BE=85=E5=8A=A9=E7=B1=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 实现了采样位图解码功能,支持指定宽高要求 - 添加了计算采样大小的算法,优化内存使用 - 设置位图配置为RGB_565以减少内存占用 - 包含边界检查防止无效参数导致异常 - 提供了高效的图片加载解决方案 --- .../brain/glass/helper/BitmapDecodeHelper.kt | 41 +++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 app/src/main/java/com/nova/brain/glass/helper/BitmapDecodeHelper.kt diff --git a/app/src/main/java/com/nova/brain/glass/helper/BitmapDecodeHelper.kt b/app/src/main/java/com/nova/brain/glass/helper/BitmapDecodeHelper.kt new file mode 100644 index 0000000..ff39f15 --- /dev/null +++ b/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) + } +}