Adam Skrášek
Adam Skrášek

Reputation: 43

UWP Binding image from local folders

My app takes a photo using the Camera and saves it like this C:\Users...\Pictures\file.PNG. I have an object with string "C:\Users\...\Pictures\file.PNG" and binding set to that string, but it does not load the Image. If i place the image to Assets and set the string to "Assets\file.png" it works. Is it possible to bind outside of Assets?

Upvotes: 0

Views: 1048

Answers (1)

krs
krs

Reputation: 599

First of all you need to realize that you do not have access to file system as e.g. in Win32 apps. So the full path in UWP app is not relevant anymore. Please take a look on this link to explain it more and nice one here.

I assume you're using Image control to display image. Something like:

MainPage.xaml

<Page
    x:Class="App1.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:App1"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    Loaded="MainPage_OnLoaded">

    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <Image Name="Img1" />
    </Grid>
</Page>

MainPage.xaml.cs

    private async void MainPage_OnLoaded(object sender, RoutedEventArgs e)
    {
        var file = await Windows.Storage.KnownFolders.CameraRoll.GetFileAsync("p1.png");
        using (var imgStream = await file.OpenStreamForReadAsync())
        {
            var bitmapImg = new BitmapImage();
            bitmapImg.SetSource(imgStream.AsRandomAccessStream());
            Img1.Height = bitmapImg.PixelHeight; //Need to take care of proper image-scaling here
            Img1.Width = bitmapImg.PixelWidth;  //Need to take care of proper image-scaling here
            Img1.Source = bitmapImg;
        }
    }

When you understand file-access concept files in UWP, you can take closer look on built-in camera control support. There's also example how to directly access captured image without hassling with file names.

Upvotes: 3

Related Questions