如何将照片从 imageview 保存到图库 android xamarin

how to save photo from image view to gallerry android xamarin

你好,我是 xamarin 的新手,我试图在互联网上找到很多代码,但它不起作用。

在我的图像视图中有点菜单,当用户在图像视图中单击菜单时,他们可以转发照片或分享照片但不能保存。

我想在里面添加保存照片的功能,但是不知道,这是我分享和转发的部分代码

public async void OnSelection(MaterialDialog dialog, View itemView, int position, string itemString)
    {
        try
        {
            if (itemString == GetText(Resource.String.Lbl_MessageInfo))
            {
                var intent = new Intent(this, typeof(MessageInfoActivity));
                intent.PutExtra("UserId", Id);
                intent.PutExtra("MainChatColor", !string.IsNullOrEmpty(MesData.ChatColor) ? MesData.ChatColor : AppSettings.MainColor ?? AppSettings.MainColor);
                intent.PutExtra("SelectedItem", JsonConvert.SerializeObject(MesData));
                StartActivity(intent);
            }
            else if (itemString == GetText(Resource.String.Lbl_Forward))
            {
                var intent = new Intent(this, typeof(ForwardMessagesActivity));
                intent.PutExtra("SelectedItem", JsonConvert.SerializeObject(MesData));
                StartActivity(intent);
            }
            else if (itemString == GetText(Resource.String.Lbl_Share))
            {
                string urlImage = MediaFile;
                var fileName = urlImage?.Split('/').Last();

                await ShareFileImplementation.ShareRemoteFile(urlImage, urlImage, fileName, GetText(Resource.String.Lbl_SendTo));
            }
            
        catch (Exception e)
        {
            Methods.DisplayReportResultTrack(e);
        }
    }

以下代码在 Android10.0(Android Q) 之前有效。

//get the data 
ImageView image = FindViewById<ImageView>(Resource.Id.image);
Bitmap bitmap = ((BitmapDrawable)image.Drawable).Bitmap;
MemoryStream baos = new MemoryStream();
bitmap.Compress(Bitmap.CompressFormat.Jpeg, 100, baos);
imageInByte = baos.ToArray();

//store it in gallery
Java.IO.File storagePath = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryPictures);
string path = System.IO.Path.Combine(storagePath.ToString(), "abc.png");
System.IO.File.WriteAllBytes(path, imageInByte);
var mediaScanIntent = new Intent(Intent.ActionMediaScannerScanFile);
mediaScanIntent.SetData(Android.Net.Uri.FromFile(new Java.IO.File(path)));
this.SendBroadcast(mediaScanIntent);

然而,GetExternalStoragePublicDirectory 已从 Android Q 中弃用,似乎自从 Android 11 我们无法将文件写入 public 外部存储,包括图库,它只是允许将文件放在应用程序自己的独立共享存储中。

参考文档: https://developer.android.com/reference/android/os/Environment#getExternalStoragePublicDirectory(java.lang.String).