Files
PostPad/src/main/java/com/shitoucuo/postpad/ImageUtils.kt

98 lines
3.3 KiB
Kotlin
Raw Normal View History

package com.shitoucuo.postpad
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import android.provider.OpenableColumns
import android.util.LruCache
/**
* 相册取图的读取、缩略图与文件名处理。
* 不引第三方图片库,自己按 inSampleSize 采样,避免大图 OOM。
*/
object ImageUtils {
data class PickedImage(val uri: Uri, val name: String, val mime: String)
/**
* 缩略图按字节限额缓存(8MB)。
* 原来每渲染一次配图条就要重新解码全部缩略图,删图时会重解 N-1 张;
* 有了缓存,同一张图在多次重建里只解一次。
*/
private val thumbCache = object : LruCache<String, Bitmap>(8 * 1024 * 1024) {
override fun sizeOf(key: String, value: Bitmap): Int = value.byteCount
}
fun picked(context: Context, uri: Uri): PickedImage =
PickedImage(uri, displayName(context, uri), mimeOf(context, uri))
fun displayName(context: Context, uri: Uri): String {
var name = ""
try {
context.contentResolver
.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null)
?.use { cursor ->
if (cursor.moveToFirst()) {
val index = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)
if (index >= 0) name = cursor.getString(index) ?: ""
}
}
} catch (e: Exception) {
// 少数 provider 不给名字,下面用时间戳兜底
}
if (name.isBlank()) {
name = "image-${System.currentTimeMillis()}.jpg"
}
return name.replace(Regex("[\"\\r\\n]"), "_")
}
fun mimeOf(context: Context, uri: Uri): String =
context.contentResolver.getType(uri) ?: "image/jpeg"
fun readBytes(context: Context, uri: Uri): ByteArray {
context.contentResolver.openInputStream(uri)?.use { stream ->
return stream.readBytes()
}
throw IllegalStateException("读取图片失败,可能已失去访问权限")
}
fun loadThumbnail(context: Context, uri: Uri, maxSize: Int): Bitmap? {
val key = "$uri@$maxSize"
thumbCache.get(key)?.let { return it }
val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
try {
context.contentResolver.openInputStream(uri)?.use {
BitmapFactory.decodeStream(it, null, bounds)
}
} catch (e: Exception) {
return null
}
val options = BitmapFactory.Options().apply {
inSampleSize = sampleSize(bounds.outWidth, bounds.outHeight, maxSize)
}
val bitmap = try {
context.contentResolver.openInputStream(uri)?.use {
BitmapFactory.decodeStream(it, null, options)
}
} catch (e: Exception) {
null
}
if (bitmap != null) thumbCache.put(key, bitmap)
return bitmap
}
private fun sampleSize(width: Int, height: Int, maxSize: Int): Int {
if (width <= 0 || height <= 0 || maxSize <= 0) return 1
var longest = maxOf(width, height)
var sample = 1
while (longest / 2 >= maxSize) {
longest /= 2
sample *= 2
}
return sample
}
}