问题描述
我有 Xamarin.forms 应用程序。一些图像来自互联网。我有“下载”按钮。当我点击按钮时,图像会保存在某个文件夹中。但不会出现在图库中。
这是代码:
public class MediaService : IMediaService
{
Context CurrentContext => CrossCurrentActivity.Current.Activity;
private readonly string path = Path.Combine(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath,"Android","data","com.mob.drift","files","Pictures");
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);
var imagePath = path + "/Images";
var imageFilePath = Path.Combine(imagePath,"img.jpg");
//Check if the imageDirectory Exists
if (!Directory.Exists(imagePath))
{
Directory.CreateDirectory(imagePath);
}
else
{
System.IO.File.WriteallBytes(imageFilePath,imageByte);
MediaScannerConnection.ScanFile(Android.App.Application.Context,new string[] { imageFilePath,path },null,null);
}
}
catch (Exception ex)
{
}
}
}
MediaScannerConnection.ScanFile 不扫描图像。请帮忙
解决方法
根据我的测试,我认为您使用了错误的路径。你可以使用下面的代码,你可以在应用程序文件夹中找到图像。
媒体服务:
Context CurrentContext => CrossCurrentActivity.Current.Activity;
public void SaveImageFromByte(byte[] imageByte,string filename)
{
try
{
var storagePath = Application.Context.GetExternalFilesDir(Android.OS.Environment.DirectoryPictures);
string path = Path.Combine(storagePath.ToString(),filename);
var imagePath = storagePath + "/Images";
var imageFilePath = Path.Combine(imagePath,filename);
//Check if the imageDirectory Exists
if (!Directory.Exists(imagePath))
{
Directory.CreateDirectory(imagePath);
System.IO.File.WriteAllBytes(imageFilePath,imageByte);
MediaScannerConnection.ScanFile(Application.Context,new string[] { imageFilePath },null,null);
}
else
{
//System.IO.File.WriteAllBytes(imageFilePath,imageByte);
//MediaScannerConnection.ScanFile(Application.Context,new string[] { "image/png","image/jpeg" },null);
}
}
catch (Exception ex)
{
}
}
下载图片:
static readonly HttpClient _client = new HttpClient();
public static Task<byte[]> DownloadImage(string imageUrl)
{
if (!imageUrl.Trim().StartsWith("https",StringComparison.OrdinalIgnoreCase))
throw new Exception("iOS and Android Require Https");
return _client.GetByteArrayAsync(imageUrl);
}
用法:
var BY = DownloadImage("https://cdn.dribbble.com/users/3701/screenshots/5557667/xamarin-studio-1_2x_4x.png");
var b = BY.Result;
DependencyService.Get<IMediaService>().SaveImageFromByte(b,"img.jpg");
检查截图: