Is there any way to fetch images as strings to UWP applications? Im trying to get my images from my database (ms-sql server) and showing them in my UWP application. I only got the names out right now, no images.. is there any way to display the "imagefile" in a image source tag in xaml?
XAML code:
<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?
Yes, there is a way to do this. Based on your description, you've got the path of the image that you want to show. Then what you need is just to open the image file as a stream and set the stream as the source of the BitmapImage
object using BitmapSource.SetSourceAsync() Method.
First of all, you have to add the Document capability in the manifest file to get permission to access the Document Library. More details here: File access permissions.
Like this:
<Capabilities>
<Capability Name="internetClient" />
<uap:Capability Name="documentsLibrary"/>
</Capabilities>
Then you could get the image file and open it as stream.
Here is the sample code that you could refer to:
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;
}