如何从 URL 下载图像并将其保存到本地 SQLite 数据库

Bra*_*ick 5 c# sqlite xamarin xamarin.forms

在 Xamarin 中,如何从 URL 下载图像?

然后,如何将图像保存到设备上的本地 SQLite 数据库?

我的 Xamarin.Forms 应用程序当前遵循Xamarin 文档以将 URL 用于 的ImageSource属性Image,这工作正常。但是,我注意到每次应用程序启动时,它都会通过网络重新下载此图像。我更喜欢从 URL 下载一次图像并将其保存到本地设备;此方法将为用户节省电池和数据使用量。

Bra*_*ick 9

解释

为此,我们将从 Url 下载图像作为byte[]using HttpClient,然后将其保存到我们的本地 SQLite 数据库。

示例应用程序

这是使用 Xamarin.Forms 完成此操作的示例应用程序。为了更好地理解,我建议从 GitHub 下载代码。

示例代码

从 URL 下载图像

我们将下载图像作为byte[]using HttpClient. 这样可以更轻松地将其存储在我们的 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;
         }
    }
Run Code Online (Sandbox Code Playgroud)

将模型保存到数据库

将图像作为 下载后byte[],我们会将其存储在 SQLite 数据库中。

我在下一节中添加了有关该模型的更多信息。

public static async Task SaveDownloadedImage(DownloadedImageModel downloadedImage)
{
    var databaseConnection = await GetDatabaseConnectionAsync();
    await databaseConnection.InsertOrReplaceAsync(downloadedImage);
}
Run Code Online (Sandbox Code Playgroud)

模型

在模型中,我创建了一个将图像存储为字符串的属性和一个将图像作为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;
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 不要在 using 语句中使用 HttpClient。将其视为共享资源并尽可能多地重用它。在将大图像加载到内存中时也要小心。最好将其保存到文件中,而只需将数据库指向路径即可。 (2认同)