我正在使用Xamarin Forms(使用iOS和Android)。我想做的是允许用户使用DependencyService从URL下载图像。我尝试在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);
}
}
如果要将图像保存到图库中,请遵循以下代码。
首先,在PCL中创建Create IMediaService接口。
public interface IMediaService
{
void SaveImageFromByte(byte[] imageByte,string filename);
}
然后在特定于平台的环境中实现此接口Xamarin.Android项目
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项目
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软件包管理器中安装NuGet软件包(Plugin.CurrentActivity),还要检查外部存储权限。