Xamarin Forms сохраняет изображение из URL в галерею устройства - PullRequest
0 голосов
/ 10 марта 2020

Я работаю над формами Xamarin (с iOS и Android). Я хочу разрешить пользователям загружать изображения с URL-адреса с помощью DependencyService. Я попытался запустить в эмуляторе IOS, и изображение сохранилось в эмуляторе, но не отображается в галерее. Ценю помощь в этом и следующем мой код:

В ViewModel:

        public void DownloadImage()
        {
            IFileService fileSvc = DependencyService.Get<IFileService>();

            WebClient wc = new WebClient();
            byte[] bytes = wc.DownloadData(ImgUrl);
            Stream stream = new MemoryStream(bytes);

            fileSvc.SavePicture(DateTime.Now.ToString(), stream, "temp");

        }

В Xamarin. iOS

        public void SavePicture(string name, Stream data, string location = "temp")
        {
            var documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
            string imageFilename = Path.Combine(documentsPath, "Images", location);
            Directory.CreateDirectory(imageFilename);

            string filePath = Path.Combine(documentsPath, name);

            byte[] bArray = new byte[data.Length];
            using (FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate))
            {
                using (data)
                {
                    data.Read(bArray, 0, (int)data.Length);
                }
                int length = bArray.Length;
                fs.Write(bArray, 0, length);
            }
        }

В Xamarin.Droid

        public void SavePicture(string name, Stream data, string location = "temp")
        {
            var documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
            documentsPath = Path.Combine(documentsPath, "Images", location);
            Directory.CreateDirectory(documentsPath);

            string filePath = Path.Combine(documentsPath, name);

            byte[] bArray = new byte[data.Length];
            using (FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate))
            {
                using (data)
                {
                    data.Read(bArray, 0, (int)data.Length);
                }
                int length = bArray.Length;
                fs.Write(bArray, 0, length);
            }
        }

1 Ответ

0 голосов
/ 11 марта 2020

Если вы хотите сохранить изображение в галерее, следуйте приведенному ниже коду.

Сначала создайте интерфейс IMediaService в PCL.

  public interface IMediaService
{
    void SaveImageFromByte(byte[] imageByte,string filename);
}

Затем внедрите этот интерфейс в Platform- специфический Xamarin. Android Project

 public  class MediaService : IMediaService
{
    Context CurrentContext => CrossCurrentActivity.Current.Activity;
    public void SaveImageFromByte(byte[] imageByte, string filename)
    {
        try
        {
            Java.IO.File storagePath = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryPictures);
            string path = System.IO.Path.Combine(storagePath.ToString(), filename);
            System.IO.File.WriteAllBytes(path, imageByte);
            var mediaScanIntent = new Intent(Intent.ActionMediaScannerScanFile);
            mediaScanIntent.SetData(Android.Net.Uri.FromFile(new Java.IO.File(path)));
            CurrentContext.SendBroadcast(mediaScanIntent);
        }
        catch (Exception ex)
        {

        }
    }
}

реализует этот интерфейс в специфичном для платформы Xamarin. iOS Project

public class MediaService : IMediaService
{
    public void SaveImageFromByte(byte[] imageByte,string fileName)
    {
        var imageData = new UIImage(NSData.FromArray(imageByte));
        imageData.SaveToPhotosAlbum((image, error) =>
        {
            //you can retrieve the saved UI Image as well if needed using  
            //var i = image as UIImage;  
            if (error != null)
            {
                Console.WriteLine(error.ToString());
            }
        });
    }
}

Для доступа к CurrentContext Установите пакет NuGet ( Plugin.CurrentActivity ) из NuGet Package Manager, также проверьте наличие разрешения для внешнего хранилища .

...