Xamarin Android如何打开图片文件并在ImageView中显示
代码问题分析与修复方案
你的代码存在3个核心错误,是导致ImageView无显示的根本原因:
- 错误处理
ACTION_OPEN_DOCUMENT返回的Uri:该Intent返回的是content://类型的共享Uri,不是本地文件的file://Uri,你直接取data.Data.Path转换成本地File的逻辑完全无效,尤其Android 10及以上的分区存储机制禁止直接通过路径访问其他应用/共享目录下的文件,会拿到无效路径或者触发权限拒绝。 - BitmapFactory.Options用法错误:
OutWidth、OutHeight是解码后的输出属性,你直接赋值无法实现按ImageView尺寸缩放图片的效果,没有正确配置采样率的前提下,大图解码可能直接返回null。 - 解码方式不匹配:
BitmapFactory.DecodeFile只能处理本地文件绝对路径,无法读取content Uri对应的资源,需要通过ContentResolver打开Uri的输入流完成解码。
修复后的OnActivityResult代码
protected override void OnActivityResult(int requestCode, [GeneratedEnum] Result resultCode, Intent data) { base.OnActivityResult(requestCode, resultCode, data); if (resultCode == Result.Ok && requestCode == 899 && data?.Data != null) { Android.Net.Uri imageUri = data.Data; try { // 先获取ImageView的尺寸 int targetW = imageView.Width; int targetH = imageView.Height; // 第一步:仅解码图片边界获取原始尺寸 BitmapFactory.Options options = new BitmapFactory.Options(); options.InJustDecodeBounds = true; using (var inputStream = ContentResolver.OpenInputStream(imageUri)) { BitmapFactory.DecodeStream(inputStream, null, options); } // 计算采样率 int inSampleSize = 1; if (options.OutWidth > targetW || options.OutHeight > targetH) { int halfWidth = options.OutWidth / 2; int halfHeight = options.OutHeight / 2; while ((halfWidth / inSampleSize) >= targetW && (halfHeight / inSampleSize) >= targetH) { inSampleSize *= 2; } } // 第二步:按采样率解码真实图片 options.InJustDecodeBounds = false; options.InSampleSize = inSampleSize; Bitmap bitmap; using (var inputStream = ContentResolver.OpenInputStream(imageUri)) { bitmap = BitmapFactory.DecodeStream(inputStream, null, options); } if (bitmap != null) { imageView.SetImageBitmap(bitmap); Toast.MakeText(this, "图片加载成功", ToastLength.Short).Show(); } else { Toast.MakeText(this, "图片加载失败", ToastLength.Short).Show(); } } catch (Exception e) { Toast.MakeText(this, "加载出错:" + e.Message, ToastLength.Short).Show(); } } }
补充说明
你启动文件选择器的代码没有问题,ACTION_OPEN_DOCUMENT会自动授予你对应Uri的临时访问权限,不需要额外申请存储读写权限。
内容的提问来源于stack exchange,提问作者user16612111
相关产品推荐
相关产品推荐

