This commit is contained in:
2026-03-03 18:31:55 +08:00
parent 9a7939d2ac
commit f219c57fad
3 changed files with 65 additions and 7 deletions
@@ -2,6 +2,8 @@ package com.sw.inbound.utils
import android.content.ContentUris
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import android.os.Build
import android.provider.MediaStore
@@ -156,4 +158,45 @@ object FileUtils {
false
}
}
/**
* 将 File 转换为 Bitmap
* @param file 图片文件
* @param reqWidth 目标宽度(用于采样压缩,0 表示不压缩)
* @param reqHeight 目标高度(用于采样压缩,0 表示不压缩)
* @return 解码后的 Bitmap,失败返回 null
*/
fun fileToBitmap(file: File, reqWidth: Int = 0, reqHeight: Int = 0): Bitmap? {
if (!file.exists() || !file.isFile) return null
return if (reqWidth > 0 && reqHeight > 0) {
// 带采样压缩,避免 OOM
val options = BitmapFactory.Options().apply {
inJustDecodeBounds = true
BitmapFactory.decodeFile(file.absolutePath, this)
inSampleSize = calculateInSampleSize(this, reqWidth, reqHeight)
inJustDecodeBounds = false
}
BitmapFactory.decodeFile(file.absolutePath, options)
} else {
BitmapFactory.decodeFile(file.absolutePath)
}
}
/**
* 计算采样率
*/
private fun calculateInSampleSize(options: BitmapFactory.Options, reqWidth: Int, reqHeight: Int): Int {
val (height, width) = options.outHeight to options.outWidth
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 inSampleSize
}
}