Xamarin.Forms:如何下载图像,将其保存在本地并在屏幕上显示? [英] Xamarin.Forms: How to download an Image, save it locally and display it on screen?

查看:193
本文介绍了Xamarin.Forms:如何下载图像,将其保存在本地并在屏幕上显示?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Android的本机应用程序中打开JPG文件时遇到问题. 我正在使用最新版本的Xamarin Essentials,有一些称为Launcher的功能. 这是我的代码

I have an issue with opening JPG file in native application on Android. I'm using newest release of Xamarin Essentials, there is some functionality called Launcher. Here is my code

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

我的本​​地路径是存储在Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);中的文件.

My local path is file stored in Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);.

每当我尝试打开该文件时,我都会报错:

Whenever I try to open that file I am getting error:

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

我在stackoverflow上找到了几种解决方案,但是我不想使用Intent,因为我的应用程序被设计为跨平台的(如果可能的话,我希望避免使用本机平台编码).

I found several solutions here on stackoverflow, but I don't want to use Intent because my application is designed to be cross-platform (I would like to avoid native platform coding if this possible).

Launcher也在iOS上引发错误:

Launcher throws error on iOS also:

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

我在做什么错了?

推荐答案

步骤1:下载图片

我们可以使用HttpClient下载图像.

HttpClient.GetByteArrayAsync将检索图像数据并将其保存在内存中.

HttpClient.GetByteArrayAsync will retrieve the image data and save it in memory.

在下面的DownloadImage中,我们将图像检索为byte[].

In DownloadImage below, we will retrieve the image as a 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步将映像保存到磁盘

现在我们已经下载了图像,我们将其保存到磁盘中.

Step 2 Save Image to Disk

Now that we've downloaded the image, we will save it to disk.

Xamarin.Essentials.Preferences允许我们使用键值对将项目保存到磁盘.由于byte[]只是指向内存的指针,因此我们必须先将byte[]转换为base64字符串,然后才能将其保存到磁盘.

Xamarin.Essentials.Preferences allows us to save items to disk using key-value pairs. Since byte[] is just a pointer to memory, we'll have to first convert the byte[] to base64-string before we can save it to disk.

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步检索要显示的图像

现在我们已经下载了图像并将其保存到磁盘,我们需要能够从磁盘检索图像以将其显示在屏幕上.

Step 3 Retrieve the Image for Display

Now that we've downloaded the image and saved it to disk, we need to be able to retrieve the image from disk to display it on the screen.

GetFromDisk从磁盘检索图像并将其转换为Xamarin.Forms.ImageSource.

GetFromDisk below retrieves the image from disk and converts it to 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);
    }
}

这篇关于Xamarin.Forms:如何下载图像,将其保存在本地并在屏幕上显示?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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