如何从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
相关产品推荐
相关产品推荐

