How to Download Image From Url and Save It to a Local SQLite Database

前端 未结 1 747
梦如初夏
梦如初夏 2020-12-11 06:38

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

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

My Xamarin.Forms app curre

相关标签:
1条回答
  • 2020-12-11 07:24

    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.

    Sample App

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

    Sample Code

    Download Image From Url

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

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

    Model

    In the model, I've created a property that stores the image as a string and a read-only property that returns the Image as a 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;
                }
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题