簡體   English   中英

Xamarin.Forms:如何下載圖像,將其保存在本地並在屏幕上顯示?

[英]Xamarin.Forms: How to download an Image, save it locally and display it on screen?

我在 Android 上的本機應用程序中打開 JPG 文件時遇到問題。 我正在使用最新版本的 Xamarin Essentials,有一些名為 Launcher 的功能。 這是我的代碼

await Launcher.TryOpenAsync("file:///" + localPath);

我的本地路徑是存儲在Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);文件Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); .

每當我嘗試打開該文件時,都會出現錯誤:

file:////data/user/0/mypackagename/files/.local/share/Screenshot.jpg exposed beyond app through Intent.getData()

我在 stackoverflow 上找到了幾個解決方案,但我不想使用 Intent,因為我的應用程序被設計為跨平台的(如果可能的話,我想避免原生平台編碼)。

Launcher 在 iOS 上也拋出錯誤:

canOpenURL: failed for URL: ** -- file:///" - error: "This app is not allowed to query for scheme file

我在這里做錯了什么?

第 1 步:下載圖像

我們可以使用HttpClient來下載圖片。

HttpClient.GetByteArrayAsync將檢索圖像數據並將其保存在內存中。

在下面的DownloadImage中,我們將檢索圖像作為byte[]

static class ImageService
{
    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);
    }
}

步驟 2 將圖像保存到磁盤

現在我們已經下載了圖像,我們將把它保存到磁盤。

Xamarin.Essentials.Preferences允許我們使用鍵值對將項目保存到磁盤。 由於byte[]只是一個指向內存的指針,我們必須先將byte[]轉換為 base64 字符串,然后才能將其保存到磁盤。

static class ImageService
{
    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);
    }

    public static void SaveToDisk(string imageFileName, byte[] imageAsBase64String)
    {
        Xamarin.Essentials.Preferences.Set(imageFileName, Convert.ToBase64String(imageAsBase64String));
    }
}

步驟 3 檢索要顯示的圖像

現在我們已經下載了圖像並將其保存到磁盤,我們需要能夠從磁盤檢索圖像以將其顯示在屏幕上。

下面的GetFromDisk從磁盤檢索圖像並將其轉換為Xamarin.Forms.ImageSource

static class ImageService
{
    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);
    }

    public static void SaveToDisk(string imageFileName, byte[] imageAsBase64String)
    {
        Xamarin.Essentials.Preferences.Set(imageFileName, Convert.ToBase64String(imageAsBase64String));
    }

    public static Xamarin.Forms.ImageSource GetFromDisk(string imageFileName)
    {
        var imageAsBase64String = Xamarin.Essentials.Preferences.Get(imageFileName, string.Empty);

        return ImageSource.FromStream(() => new MemoryStream(Convert.FromBase64String(imageAsBase64String)));
    }
}

示例:在Xamarin.Forms.ContentPage使用ImageService

class App : Application
{
    public App() => MainPage = new MyPage();
}

class MyPage : ContentPage
{
    readonly Image _downloadedImage = new Image();

    public MyPage()
    {
        Content = _downloadedImage;
    }

    protected override  async void OnAppearing()
    {
        const string xamrainImageUrl = "https://cdn.dribbble.com/users/3701/screenshots/5557667/xamarin-studio-1_2x_4x.png"
        const string xamarinImageName = "XamarinLogo.png";

        var downloadedImage = await ImageService.DownloadImage(xamrainImageUrl);

        ImageService.SaveToDisk(xamarinImageName, downloadedImage);

        _downloadedImage.Source = ImageService.GetFromDisk(xamarinImageName);
    }
}

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM