Image.Source property

Applies to Windows and Windows Phone

Gets or sets the source for the image.

Syntax


public ImageSource Source { get; set; }


<Image Source="uri"/>

XAML Values

uri

The URI location of the image source file. In XAML syntax, you can specify what appears to be a relative URI that is relative to a base URI. The base URI is interpreted based on the location of the XAML file that loads it, and uses the ms-appx: scheme implicitly. For more info see Remarks.

Property value

Type: ImageSource

An object that represents the image source file for the drawn image. Typically you set this with a BitmapImage object, constructed with the URI that describes the path to a valid image source file. Or, you can initialize a BitmapSource with a stream, perhaps a stream from a storage file.

Remarks

Setting the Source property is inherently an asynchronous action. Because it's a property, there isn't an awaitable syntax, but for most scenarios you don't need to interact with the asynchronous aspects of image source file loading. The framework will wait for the image source to be returned, and will rerun layout when the image source file becomes available.

Setting the source to a URI value that can't be resolved to a valid image source file does not throw an exception. Instead, it fires an ImageFailed event. Decoding failures also fire ImageFailed. You can write an ImageFailed handler and attach it to the Image object to detect this, and possibly use the ErrorMessage in event data to determine the nature of the failure. Also, if you want to verify that an image source file was loaded correctly, you can handle the ImageOpened event on the Image element.

Setting Source in XAML

You can set the Source property as an attribute in XAML. In this case, you're setting the Source attribute value as a URI string that describes the location of the source image file. This behavior relies on underlying type conversion that processes the string as a URI, and calls the equivalent of the BitmapImage(Uri) constructor. Setting the Source property using a URI string is a shortcut enabled by XAML. Note that the URI here appears to be a relative URI; supporting partial URIs is another XAML shortcut.


<Image Width="200" Source="Images/myImage.png"/>

The XAML parser interprets any strings that represent a relative URI using the base URI of the XAML page that is being parsed. For example, if you specify a value "Images/myImage.png" in XAML, that string is interpreted as a relative path suffix that is appended to the base URI location within the app package where the XAML page itself exists. If the previous Image element is added to a page that’s in the root of the app package, the URI is interpreted as ms-appx:///Images/myImage.png. If the Image is added to a page that’s in a Pages folder in the app, the URI is interpreted as ms-appx:///Pages/Images/myImage.png.

If the source image is not part of the app package, you must use an absolute URI to set the Source property in XAML. For more info, see How to load file resources, and examples later in this document.

A property element syntax in XAML is also possible, specifying a BitmapImage object element with valid source as the property value.

Setting Source in code

To set the Image.Source property in code requires an instance of BitmapImage (or BitmapSource), which you also must construct. If your image source is a stream, use the async SetSourceAsync method of BitmapImage to define the image information from the stream. For more info, see the Using a stream source to show images from the Pictures library section.

If your image source is a file referenced by URI, set the BitmapImage.UriSource property, or use the BitmapImage constructor that takes a URI parameter. The Windows Runtime enforces that a URI must be absolute; you can't use relative URIs in Windows Runtime code. If you are using a .NET Framework System.Uri value, and you use a signature that requires a UriKind value, make sure to specify Absolute.

When you reference local content, you must include the ms-appx: scheme in the absolute URI that you use as the BitmapImage.UriSource. In code, you don't get the processing shortcuts for combining relative URI parts and the ms-appx: scheme that happens automatically if you specify Source as a XAML attribute. Instead you must explicitly construct an absolute URI with the appropriate scheme.

Here's how to set the source to an image from the app package.



Image img = new Image();
BitmapImage bitmapImage = new BitmapImage();
Uri uri = new Uri("ms-appx:///Assets/Logo.png");
bitmapImage.UriSource = uri;
img.Source = bitmapImage;

// OR

Image img = new Image();
img.Source = new BitmapImage(new Uri("ms-appx:///Assets/Logo.png"));


If you need to ensure that the Image control is ready before trying to use it in code, handle the Loaded event, and set the Source property in the event handler.

Note  The Loaded event occurs when the Image control is loaded into the XAML page. The ImageOpened event occurs when the image file is opened in the Image control.

Here's an example of setting Image.Source in the handler for the Loaded event. In this example, the Image object was created in XAML but doesn't have a source or any other property values; instead these values are provided at run-time when the Image is loaded from XAML.


<Image Loaded="Image_Loaded"/>


void Image_Loaded(object sender, RoutedEventArgs e)
{
    Image img = sender as Image;
    if (img != null)
    {
        BitmapImage bitmapImage = new BitmapImage();
        img.Width = bitmapImage.DecodePixelWidth = 280;
        bitmapImage.UriSource = new Uri("ms-appx:///Assets/Logo.png");
        img.Source = bitmapImage;
    }
}

You can handle the ImageOpened event if there are any timing issues with retrieving or decoding the image source, where you might need alternate content to display until the image source is available. See XAML images sample for example code.

Using a relative URI in code

We saw previously that the XAML parser interprets a relative URI using the base URI of the XAML page that is being parsed. To achieve the same result in code, you can construct a Uri using one of the constructors that creates a URI by combining an absolute base and then a relative path within that location. For the first parameter, call BaseUri on Page where the Image is loaded. (You can also call BaseUri on the Image instance where you are setting the source, or another element on the page. See the Caution below.) This creates a URI with the ms-appx: scheme and adds the path that is part of the XAML page's location. For the second parameter, pass the relative URI string that describes the source image location.

In C# or Microsoft Visual Basic, the Uri type is projected as System.Uri, so use the System.Uri(Uri, String) constructor that takes a string as the second parameter. In Visual C++ component extensions (C++/CX) use Uri(String,String).


<Image x:Name="capturedPhoto"/>



BitmapImage bitmapImage = new BitmapImage();
// Call BaseUri on the root Page element and combine it with a relative path
// to consruct an absolute URI.
bitmapImage.UriSource = new Uri(this.BaseUri, "Assets/placeholder.png");
capturedPhoto.Source = bitmapImage;

Caution  

If you instantiate a new Image in code, the BaseUri property is null until the Image is added to the visual tree of the a page. For example, the following code throws an ArgumentNull exception. To avoid the exception, add the Image to the visual tree before setting the Source property.

This example throws an exception because it calls BaseUri on the Image before the Image is added to the page. It's assumed that 'stackPanel1' is a StackPanel element declared in XAML.



Image img = new Image();
BitmapImage bitmapImage = new BitmapImage();

// AN EXCEPTION IS THROWN BECAUSE img.BaseUri IS NULL AT THIS POINT.
Uri uri = new Uri(img.BaseUri, "Assets/Logo.png");

bitmapImage.UriSource = uri;
img.Source = bitmapImage;
stackPanel1.Children.Add(img);

To avoid this error, you can call BaseUri on the Page itself, as shown previously, or add the Image to the page before calling BaseUri, as shown here.

In this example, the Image is added to the page before the call to BaseUri, so BaseUri is not null. It's assumed that 'stackPanel1' is a StackPanel element declared in XAML.



Image img = new Image();
// Add the image to the page.
stackPanel1.Children.Add(img);

BitmapImage bitmapImage = new BitmapImage();
// img.BaseUri in not null because img has been added to the page.
Uri uri = new Uri(img.BaseUri, "Assets/Logo.png");
bitmapImage.UriSource = uri;
img.Source = bitmapImage;


Using files from a network

To use a file from a network location as an image source, use the http: or https: schemes, as shown here. Specify the absolute URI. For more info, see How to load file resources.


<Image Source="http://www.contoso.com/images/logo.png"/>



Image img = new Image();
img.Source = new BitmapImage(new Uri("http://www.contoso.com/images/logo.png"));


Using files from local storage

To use files that are placed in your app's local storage as an image source , use the ms-appdata: scheme, as shown here. Specify the absolute URI. For more info, see How to load file resources.



<!-- Access an image file stored in the local folder -->
<Image Source="ms-appdata:///local/images/logo.png"/>

<!-- Access an image file stored in the roaming folder -->
<Image Source="ms-appdata:///roaming/images/logo.png"/>

<!-- Access an image file stored in the temp folder -->
<Image Source="ms-appdata:///temp/images/logo.png"/>



var uri = new System.Uri("ms-appdata:///local/images/logo.png");
var file = await Windows.Storage.StorageFile.GetFileFromApplicationUriAsync(uri);

Image img = new Image();
img.Source = file;

Using a stream source to show images from the Pictures library

A typical use of Image elements in an app is to show pictures from the user’s Pictures library. These pictures might be accessed programmatically or through a FileOpenPicker. In either case, the StorageFile object you get can be opened as a stream, but doesn't provide a URI reference to the image file. To use a stream as an image source, you must write code that sets your Image instance to use the stream. This can't be done in XAML alone.

To display an individual image, use the StorageFile objects from enumerating the library and call OpenAsync to obtain a stream. Use this stream to set the image source, by creating a new BitmapImage, then calling SetSourceAsync and passing the stream to use as the streamSource parameter.

This example shows how to use a FileOpenPicker to access an image file from the Pictures library and set it as the Source of an Image control. The code is already awaitable because it's waiting for the user to choose a file and it only runs after that happens. The stream to use comes from StorageFile.OpenAsync after a StorageFile instance is returned from the async picker actions. For more info on using file pickers, see Quickstart: Accessing files with file pickers.

  • Applies to Windows Phone

Windows Phone Using a file picker on Windows Phone requires additional steps that are beyond the scope of this example. For more info, see How to continue your Windows Phone app after calling a file picker.



<Button Content="Get photo" Click="GetPhotoButton_Click"/>

<Image x:Name="image1" Width="300"/>


private async void GetPhotoButton_Click(object sender, RoutedEventArgs e)
{
    // Set up the file picker.
    Windows.Storage.Pickers.FileOpenPicker openPicker = 
        new Windows.Storage.Pickers.FileOpenPicker();
    openPicker.SuggestedStartLocation = 
        Windows.Storage.Pickers.PickerLocationId.PicturesLibrary;
    openPicker.ViewMode = 
        Windows.Storage.Pickers.PickerViewMode.Thumbnail;

    // Filter to include a sample subset of file types.
    openPicker.FileTypeFilter.Clear();
    openPicker.FileTypeFilter.Add(".bmp");
    openPicker.FileTypeFilter.Add(".png");
    openPicker.FileTypeFilter.Add(".jpeg");
    openPicker.FileTypeFilter.Add(".jpg");

    // Open the file picker.
    Windows.Storage.StorageFile file = 
        await openPicker.PickSingleFileAsync();

    // 'file' is null if user cancels the file picker.
    if (file != null)
    {
        // Open a stream for the selected file.
        // The 'using' block ensures the stream is disposed
        // after the image is loaded.
        using (Windows.Storage.Streams.IRandomAccessStream fileStream =
            await file.OpenAsync(Windows.Storage.FileAccessMode.Read))
        {
            // Set the image source to the selected bitmap.
            Windows.UI.Xaml.Media.Imaging.BitmapImage bitmapImage =
                new Windows.UI.Xaml.Media.Imaging.BitmapImage();

            bitmapImage.SetSource(fileStream);
            image1.Source = bitmapImage;
        }
    }
}

This example shows how to programmatically access an image file from the Pictures library and set it as the Source of an Image control. To access the content of the Pictures library programmatically, call StorageFolder.GetFilesAsync. Remember that you need to specify a capability to access the Pictures library programmatically.


protected async override void OnNavigatedTo(NavigationEventArgs e)
{
    // Get the Pictures library
    Windows.Storage.StorageFolder picturesFolder = 
        Windows.Storage.KnownFolders.PicturesLibrary;
    IReadOnlyList<StorageFolder> folders = 
        await picturesFolder.GetFoldersAsync();
    
    // Process file folders
    foreach (StorageFolder folder in folders)
    {
        // Get and process files in folder
        IReadOnlyList<StorageFile> fileList = await folder.GetFilesAsync();
        foreach (StorageFile file in fileList)
        {
            Windows.UI.Xaml.Media.Imaging.BitmapImage bitmapImage = 
                new Windows.UI.Xaml.Media.Imaging.BitmapImage();

            // Open a stream for the selected file.
            // The 'using' block ensures the stream is disposed
            // after the image is loaded.
            using (Windows.Storage.Streams.IRandomAccessStream fileStream = 
                await file.OpenAsync(Windows.Storage.FileAccessMode.Read))
            {
                // Set the image source to the selected bitmap.
                Windows.UI.Xaml.Media.Imaging.BitmapImage bitmapImage =
                    new Windows.UI.Xaml.Media.Imaging.BitmapImage();
                bitmapImage.SetSource(fileStream);

                // Create an Image control.  
                Image img = new Image();
                img.Height = 50;
                img.Source = bitmapImage;

                // Add the Image control to the UI. 'imageGrid' is a
                // VariableSizedWrapGrid declared in the XAML page.
                imageGrid.Children.Add(img);
            }
        }
    }
}

Image sources and scaling

If you are referencing images that are packaged in your app, you should create your image sources at several recommended sizes, to ensure that your app looks great when the Windows Runtime scales it. When specifying a Source for an Image as a URI, you can use a naming convention that will automatically reference the correct image resource for the current scaling as detected by the system at run-time. For specifics of the naming convention and more info, see Quickstart: Using file or image resources.

For more info on how to design for scaling, see Guidelines for scaling to pixel density or Remarks in Image.

Image sources and resource qualifiers

You can use automatic handling for accessing unqualified resources with current scale and culture qualifiers, or you can use ResourceManager and ResourceMap with qualifiers for culture and scale to obtain the resources directly. For more info see Resource management system or Remarks in Image. For more info on app resources and how to package image sources in an app, see Defining app resources.

Requirements

Minimum supported client

Windows 8

Minimum supported server

Windows Server 2012

Minimum supported phone

Windows Phone 8.1 [Windows Runtime apps only]

Namespace

Windows.UI.Xaml.Controls
Windows::UI::Xaml::Controls [C++]

Metadata

Windows.winmd

See also

Image
ImageFailed
ImageOpened
BitmapSource
Quickstart: Image and ImageBrush
XAML images sample

 

 

Show:
© 2014 Microsoft