I need a converter to convert from a Uri
into a BitmapImage
's ImageSource. If I use this:
Uri dummyUri = new Uri(@"ms-appx:///Assets/EmptyImage.png");
return new BitmapImage(dummyUri);
everything works fine, but my 'real' urls are pointing to files that are copied into a downloads dir under the LocalState folder. The Uri is:
file:///downloads/eni^mp270a^tablet test/DSC_5517.jpg
I can't make this format work! Do I have to open/read the file? I can't make the convert method async so that will make it tricky.
my 'real' urls are pointing to files that are copied into a downloads dir under the LocalState folder. The Uri is: file:///downloads/eni^mp270a^tablet test/DSC_5517.jpg
As we know, the local folder of our app is named LocalState
folder, we can access this folder in app's code behind. But the Uri here is not correct, the problem is actually "How to get the file's path in the local folder."
You can use StorageFile.Path | path property to get the full file-system path of the files here. For example here, I used a ListView
to show all the BitmapImage
s which are converted from the file's Uri. It's odd since the url can directly be used as the Image
's source, but here I just use a converter to convert url to BitmapImage
as needed.
<Page.Resources>
<local:UriToBitmapImageConverter x:Key="cvt" />
</Page.Resources>
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Grid.RowDefinitions>
<RowDefinition Height="50" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Button Content="Get Picture" Click="Button_Click" />
<ListView Grid.Row="1" ItemsSource="{x:Bind urlcollection}">
<ListView.ItemTemplate>
<DataTemplate>
<Image Source="{Binding url, Converter={StaticResource cvt}}" Width="300" Height="300" />
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Grid>
code behind:
private ObservableCollection<ImageUri> urlcollection = new ObservableCollection<ImageUri>();
public MainPage()
{
this.InitializeComponent();
}
private async void Button_Click(object sender, RoutedEventArgs e)
{
StorageFolder local = ApplicationData.Current.LocalFolder;
StorageFolder downloads = await local.GetFolderAsync("downloads");
if (downloads != null)
{
var files = await downloads.GetFilesAsync();
foreach (var file in files)
{
urlcollection.Add(new ImageUri { url = new Uri(file.Path) });
}
}
}
Converter is like this:
public class UriToBitmapImageConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
var url = (Uri)value;
return new BitmapImage(url);
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
throw new NotImplementedException();
}
}
And the ImageUri
class is simple:
public class ImageUri
{
public Uri url { get; set; }
}