在 Xamarin 中,如何从 URL 下载图像?
然后,如何将图像保存到设备上的本地 SQLite 数据库?
我的 Xamarin.Forms 应用目前遵循 Xamarin Documentation为 Image
的 ImageSource
属性使用 URL,这工作正常。但是,我注意到每次应用程序启动时,它都会通过网络重新下载此图像。我更愿意从 URL 下载一次图像并将其保存在本地设备上;此方法将为用户节省电池和数据使用量。
最佳答案
说明
为此,我们将使用 HttpClient
从 Url 下载图像作为 byte[]
,然后将其保存到我们的本地 SQLite 数据库。
示例应用
Here is a sample app使用 Xamarin.Forms 完成此操作。为了更好地理解,我建议从 GitHub 下载代码。
示例代码
从网址下载图片
我们将使用 HttpClient
下载图像作为 byte[]
。这将使它更容易存储在我们的 SQLite 数据库中。
const int _downloadImageTimeoutInSeconds = 15;
readonly HttpClient _httpClient = new HttpClient { Timeout = TimeSpan.FromSeconds(_downloadImageTimeoutInSeconds) };
async Task<byte[]> DownloadImageAsync(string imageUrl)
{
try
{
using (var httpResponse = await _httpClient.GetAsync(imageUrl))
{
if (httpResponse.StatusCode == HttpStatusCode.OK)
{
return await httpResponse.Content.ReadAsByteArrayAsync();
}
else
{
//Url is Invalid
return null;
}
}
}
catch (Exception e)
{
//Handle Exception
return null;
}
}
将模型保存到数据库
将图像下载为 byte[]
后,我们会将其存储在 SQLite 数据库中。
我在下一节中添加了有关该模型的更多信息。
public static async Task SaveDownloadedImage(DownloadedImageModel downloadedImage)
{
var databaseConnection = await GetDatabaseConnectionAsync();
await databaseConnection.InsertOrReplaceAsync(downloadedImage);
}
模型
在模型中,我创建了一个将图像存储为字符串的属性和一个将图像作为 Xamarin.Forms.ImageSource
返回的只读属性。
public class DownloadedImageModel
{
[PrimaryKey]
public string ImageUrl { get; set;}
public byte[] DownloadedImageBlob { get; set; }
public ImageSource DownloadedImageAsImageStreamFromBase64String
{
get
{
try
{
if (DownloadedImageBlob == null)
return null;
var imageByteArray = DownloadedImageBlob;
return ImageSource.FromStream(() => new MemoryStream(imageByteArray));
}
catch (Exception e)
{
Debug.WriteLine(e);
return null;
}
}
}
}
关于c# - 如何从 Url 下载图像并将其保存到本地 SQLite 数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41337487/