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

如何在MAUI .NET Android应用中获取图库分享图片的路径

解决MAUI Android获取分享图片路径并显示的方法

Android分享的图片URI多为content://类型,无法直接当作文件路径使用,以下提供两种可行方案:

方案一:直接读取图片流显示(推荐)

无需转换真实路径,通过ContentResolver获取图片输入流,直接转换为MAUI可识别的ImageSource,适配绝大多数场景:

修改MainActivity.cs代码,添加分享处理逻辑:

[Activity(Theme = "@style/Maui.SplashTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation | ConfigChanges.UiMode | ConfigChanges.ScreenLayout | ConfigChanges.SmallestScreenSize | ConfigChanges.Density, LaunchMode = LaunchMode.SingleTask)]
[IntentFilter(new[] { "android.intent.action.SEND" }, Categories = new[] { "android.intent.category.DEFAULT" }, DataMimeType = "image/*")]
[IntentFilter(new[] { "android.intent.action.SEND_MULTIPLE" }, Categories = new[] { "android.intent.category.DEFAULT" }, DataMimeType = "image/*")]
public class MainActivity : MauiAppCompatActivity
{
    protected override void OnNewIntent(Intent? intent)
    {
        base.OnNewIntent(intent);
        if (intent == null) return;

        // 处理单张图片分享
        if (Intent.ActionSend.Equals(intent.Action) && intent.Type?.StartsWith("image/") == true)
        {
            Uri? imageUri = intent.HasExtra(Intent.ExtraStream) 
                ? intent.GetParcelableExtra<Uri>(Intent.ExtraStream) 
                : intent.ClipData?.ItemCount > 0 ? intent.ClipData.GetItemAt(0).Uri : null;

            imageUri?.Let(LoadImageFromUri);
        }
        // 处理多张图片分享
        else if (Intent.ActionSendMultiple.Equals(intent.Action) && intent.Type?.StartsWith("image/") == true)
        {
            var imageUris = intent.GetParcelableArrayListExtra(Intent.ExtraStream) as List<Uri>;
            imageUris?.FirstOrDefault()?.Let(LoadImageFromUri);
        }
    }

    private void LoadImageFromUri(Uri imageUri)
    {
        using var inputStream = ContentResolver.OpenInputStream(imageUri);
        if (inputStream == null) return;

        var memoryStream = new MemoryStream();
        inputStream.CopyTo(memoryStream);
        memoryStream.Position = 0;

        var imageSource = ImageSource.FromStream(() => new MemoryStream(memoryStream.ToArray()));
        // 通过MessagingCenter通知MAUI层更新UI
        MessagingCenter.Send(this, "ImageReceived", imageSource);
    }
}

在MAUI的ViewModel中订阅消息,更新UI绑定:

public class MainViewModel : INotifyPropertyChanged
{
    private ImageSource _sharedImage;
    public ImageSource SharedImage
    {
        get => _sharedImage;
        set { _sharedImage = value; OnPropertyChanged(); }
    }

    public MainViewModel()
    {
        MessagingCenter.Subscribe<MainActivity, ImageSource>(this, "ImageReceived", (_, source) => SharedImage = source);
    }

    public event PropertyChangedEventHandler? PropertyChanged;
    protected void OnPropertyChanged([CallerMemberName] string propertyName = "")
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

对应的XAML布局:

<Image Source="{Binding SharedImage}" WidthRequest="300" HeightRequest="300" />

方案二:将Content URI转换为真实文件路径

仅适用于公共媒体库中的图片,通过查询MediaStore获取真实路径:

添加URI转路径的工具方法:

private string? GetRealPathFromUri(Uri uri)
{
    string[] projection = { MediaStore.Images.Media.Data };
    using var cursor = ContentResolver.Query(uri, projection, null, null, null);
    if (cursor == null || !cursor.MoveToFirst()) return null;
    
    int columnIndex = cursor.GetColumnIndexOrThrow(MediaStore.Images.Media.Data);
    return cursor.GetString(columnIndex);
}

在处理URI时调用该方法:

if (imageUri != null)
{
    string? realPath = GetRealPathFromUri(imageUri);
    if (!string.IsNullOrEmpty(realPath))
    {
        var imageSource = ImageSource.FromFile(realPath);
        MessagingCenter.Send(this, "ImageReceived", imageSource);
    }
}

权限配置

在AndroidManifest.xml中添加媒体读取权限:

<uses-permission android:name="android.permission.READ_MEDIA_IMAGES" />
<!-- 适配Android 10及以下版本 -->
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" android:maxSdkVersion="29" />

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 08:33:15