从 api 中获取图像作为字符串?到 UWP 应用程序

Fetch images from api as strings? To UWP application

有没有办法将图像作为字符串获取到 UWP 应用程序? 我试图从我的数据库(ms-sql 服务器)获取我的图像并在我的 UWP 应用程序中显示它们。我现在只知道名字,没有图像..有什么方法可以在 xaml 的图像源标签中显示“图像文件”?

我的api

XAML代码:

<Grid>
        <ListBox x:Name="lstImages">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel>
                        <TextBlock Text="{Binding Name}"></TextBlock>
                        <Image Source="{Binding ImageFile}"></Image>
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
    </Grid>
</Page>

XAML.cs

   public ObservableCollection<Games> gamesList { get; set; } = new ObservableCollection<Games>();
        public MainPage()
        {
            this.InitializeComponent();
            LoadImages();
        }

        internal async System.Threading.Tasks.Task LoadImages()
        {
            HttpClient httpClient = new HttpClient();
            string apiURL = @"http://localhost:65143/api/Games";

            HttpResponseMessage response = await httpClient.GetAsync(new Uri(apiURL));
            if (response.IsSuccessStatusCode)
            {
                string content = await response.Content.ReadAsStringAsync();
                gamesList = JsonConvert.DeserializeObject<ObservableCollection<Games>>(content);
                lstImages.ItemsSource = gamesList;
            }

        }
    }

Is there any way to fetch images as strings to UWP applications?

是的,有办法做到这一点。根据您的描述,您已经获得了要显示的图像的路径。然后你需要的只是将图像文件作为流打开并使用 BitmapSource.SetSourceAsync() Method.

将流设置为 BitmapImage 对象的源

首先,您需要在manifest文件中添加Document能力,以获得访问Document Library的权限。此处有更多详细信息:File access permissions.

像这样:

 <Capabilities>
<Capability Name="internetClient" />
<uap:Capability Name="documentsLibrary"/>
  </Capabilities>

然后您就可以获取图像文件并将其作为流打开。

这里是您可以参考的示例代码:

 StorageFolder folder = await KnownFolders.DocumentsLibrary.GetFolderAsync("uwpAppPics");
        StorageFile file = await folder.GetFileAsync("london.png");

        // Ensure the stream is disposed once the image is loaded
        using (IRandomAccessStream fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read))
        {
            // Set the image source to the selected bitmap
            BitmapImage bitmapImage = new BitmapImage();
            await bitmapImage.SetSourceAsync(fileStream);
            //MyImage is the image control
            MyImage.Source = bitmapImage;
        }