如何从 URL 下载图像并将其保存到本地 SQLite 数据库 [英] How to Download Image From Url and Save It to a Local SQLite Database

查看:34
本文介绍了如何从 URL 下载图像并将其保存到本地 SQLite 数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In Xamarin, how do you download an image from a URL?

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

And then, how do you save the image to a local SQLite database on the device?

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

My Xamarin.Forms app currently follows the Xamarin Documentation to use a URL for the ImageSource property of an Image, and this works fine. But, I've noticed that every time the app launches, it re-downloads this image over the network. I'd prefer to download the image from the URL once and save it locally to the device; this method will save battery and data usage for the user.

推荐答案

说明

为此,我们将使用 HttpClient 从 Url 以 byte[] 的形式下载图像,然后将其保存到我们的本地 SQLite 数据库中.

Explanation

To accomplish this, we'll download the image from the Url as a byte[] using HttpClient, then save it to our local SQLite database.

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

Here is a sample app that accomplishes this using Xamarin.Forms. For the best understanding, I recommend downloading the code from GitHub.

我们将使用 HttpClient 将图像下载为 byte[].这样可以更轻松地将其存储在我们的 SQLite 数据库中.

We will download the image as a byte[] using HttpClient. This will make it easier to store it in our SQLite Database.

    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 数据库中.

Save Model to Database

Once you've downloaded the image as a byte[], we'll store it in the SQLite database.

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

I've added more information about the model in the next section.

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;
            }
        }
    }
}

这篇关于如何从 URL 下载图像并将其保存到本地 SQLite 数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆