You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从Uri获取图片尺寸?Jetpack Compose实践遇阻求助

获取Android Jetpack Compose中选中图片的尺寸

两种方法失败的原因

  • 第一种方法失败:rememberAsyncImagePainter是异步加载逻辑,在图片未完成加载前,intrinsicSize会返回Unspecified,无法直接拿到真实尺寸。
  • 第二种方法失败:通过ActivityResultContracts.PickVisualMedia获取的Uri是content://类型,uri.path并非真实文件路径,BitmapFactory.decodeFile无法识别该路径,因此返回宽高为0。

可行解决方案

方案1:ContentResolver + BitmapFactory

通过ContentResolver打开Uri对应的输入流,再用BitmapFactory解析尺寸:

val context = LocalContext.current
uri?.let { contentUri ->
    val options = BitmapFactory.Options().apply {
        inJustDecodeBounds = true
    }
    context.contentResolver.openInputStream(contentUri)?.use { inputStream ->
        BitmapFactory.decodeStream(inputStream, null, options)
        val width = options.outWidth
        val height = options.outHeight
        Log.d("MyLog", "图片尺寸:$width x $height")
    }
}

方案2:ImageDecoder(Android 10+,API 29+)

使用Android推荐的现代图片解码API,支持content://类型Uri及更多格式:

val context = LocalContext.current
uri?.let { contentUri ->
    val source = ImageDecoder.createSource(context.contentResolver, contentUri)
    val decoder = ImageDecoder.decodeDrawable(source)
    val width = decoder.intrinsicWidth
    val height = decoder.intrinsicHeight
    Log.d("MyLog", "图片尺寸:$width x $height")
}

方案3:AsyncImage加载完成后获取尺寸

如果是在Compose中展示图片时需要尺寸,可利用AsyncImage的加载回调:

AsyncImage(
    model = uri,
    contentDescription = "选中的图片",
    onSuccess = { successResult ->
        val size = successResult.painter.intrinsicSize
        Log.d("MyLog", "图片尺寸:${size.width.toInt()} x ${size.height.toInt()}")
    }
)

内容的提问来源于stack exchange,提问作者Davanok

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 02:32:39