语言

Image.Source 属性

定义

获取或设置图像的源。

public:
 property ImageSource ^ Source { ImageSource ^ get(); void set(ImageSource ^ value); };
ImageSource Source();

void Source(ImageSource value);
public ImageSource Source { get; set; }
var imageSource = image.source;
image.source = imageSource;
Public Property Source As ImageSource
<Image Source="uri"/>

属性值

一个对象,表示所绘制图像的图像源文件。 通常,使用 一个 BitmapImage 对象进行设置,该对象使用统一资源标识符(URI)构造,用于描述有效图像源文件的路径。 或者,可以使用流(可能是存储文件中的流)初始化 BitmapSource 。

注解

设置 Source 属性本质上是一个异步操作。 因为它是一个属性,所以没有可等待的语法,但在大多数情况下,你不需要与图像源文件加载的异步方面进行交互。 框架将等待图像源返回,并在图像源文件可用时重新运行布局。

将源设置为无法解析为有效映像源文件的统一资源标识符(URI)值不会引发异常。 而是触发 ImageFailed 事件。 解码失败也会激发 ImageFailed。 可以编写 ImageFailed 处理程序并将其附加到 Image 对象以检测此问题,并可能在事件数据中使用 ErrorMessage 来确定失败的性质。 此外,如果要验证图像源文件是否已正确加载,则可以处理 Image 元素上的 ImageOpened 事件。

在 XAML 中设置源

可以在 XAML 中将 Source 属性设置为属性。 在这种情况下,将源属性值设置为描述源映像文件位置的统一资源标识符(URI)字符串。 此行为依赖于基础类型转换,该转换将字符串作为统一资源标识符(URI)进行处理,并调用等效的 BitmapImage(Uri) 构造函数。 使用统一资源标识符(URI)字符串设置源属性是由 XAML 启用的快捷方式。 请注意,此处的统一资源标识符(URI)似乎是相对统一资源标识符(URI):支持部分统一资源标识符(URI)是另一个 XAML 快捷方式。

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

XAML 分析程序使用所分析的 XAML 页面的基本统一资源标识符(URI)解释表示相对统一资源标识符(URI)的任何字符串。 例如,如果在 XAML 中指定值“Images/myImage.png”,该字符串将解释为追加到 XAML 页面本身所在的应用包中基统一资源标识符(URI)位置的相对路径后缀。 如果将上一 个 Image 元素添加到应用包根目录中的页面,统一资源标识符(URI)将解释为 ms-appx:///Images/myImage.png。 如果将 图像 添加到应用中的 Pages 文件夹中的页面,统一资源标识符(URI)将解释为 ms-appx:///Pages/Images/myImage.png。

如果源映像不是应用包的一部分,则必须使用绝对统一资源标识符(URI)在 XAML 中设置 Source 属性。 有关详细信息,请参阅本文档后面的 “如何加载文件资源”和示例。

还可以使用 XAML 中的属性元素语法,将具有有效源的 BitmapImage 对象元素指定为属性值。

在代码中设置源代码

若要在代码中设置 Image.Source 属性,需要 位图Image (或 BitmapSource)的实例,还必须构造该实例。 如果图像源是流,请使用 BitmapImage 的 async SetSourceAsync 方法从流中定义图像信息。

如果图像源是统一资源标识符(URI)引用的文件,请设置 BitmapImage.UriSource 属性,或使用采用统一资源标识符(URI)参数的 BitmapImage 构造函数。 Windows 运行时强制要求统一资源标识符(URI)必须是绝对的;不能在Windows 运行时代码中使用相对统一资源标识符(URI)。 如果使用 .NET Framework System.Uri 值,并且使用需要 UriKind 值的签名,请确保指定 Absolute。

引用本地内容时,必须在用作 BitmapImage.UriSource 的绝对统一资源标识符(URI)中包含 ms-appx:方案。 在代码中,无法获取用于合并相对统一资源标识符(URI)部分和 ms-appx 的 处理快捷方式:如果将 Source 指定为 XAML 属性,则会自动实现的方案。 相反,必须使用适当的方案显式构造绝对统一资源标识符(URI)。

下面介绍如何将源设置为应用包中的图像。

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"));
Windows::UI::Xaml::Controls::Image img;
Windows::UI::Xaml::Media::Imaging::BitmapImage bitmapImage;
Windows::Foundation::Uri uri{ L"ms-appx:///Assets/LockScreenLogo.png" };
bitmapImage.UriSource(uri);
img.Source(bitmapImage);

// OR

Windows::UI::Xaml::Controls::Image img;
img.Source(Windows::UI::Xaml::Media::Imaging::BitmapImage{ Windows::Foundation::Uri{ L"ms-appx:///Assets/LockScreenLogo.png" } });
auto img = ref new Image();
auto bitmapImage = ref new Windows::UI::Xaml::Media::Imaging::BitmapImage();
auto uri = ref new Windows::Foundation::Uri("ms-appx:///Assets/Logo.png");
bitmapImage->UriSource = uri;
img->Source = bitmapImage;

// OR

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

如果需要确保在尝试在代码中使用 图像 控件之前准备就绪,请处理 加载 的事件,并在事件处理程序中设置 Source 属性。

注释

当图像控件加载到 XAML 页时,将发生 FrameworkElement.Loaded 事件。 在 Image 控件中打开映像文件时,将发生 ImageOpened 事件。

下面是在 加载 事件的处理程序中设置 Image.Source 的示例。 在此示例中, Image 对象是在 XAML 中创建的,但没有源或任何其他属性值;而是在从 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;
    }
}
void MainPage::Image_Loaded(winrt::Windows::Foundation::IInspectable const& sender, winrt::Windows::UI::Xaml::RoutedEventArgs const& /* e */)
{
    auto img{ sender.as<Windows::UI::Xaml::Controls::Image>() }; // throws if QI fails, so no need for null-check afterwards.
    Windows::UI::Xaml::Media::Imaging::BitmapImage bitmapImage;
    img.Width(280);
    bitmapImage.DecodePixelWidth(280);
    bitmapImage.UriSource(Windows::Foundation::Uri{ L"ms-appx:///Assets/LockScreenLogo.png" });
    img.Source(bitmapImage);
}
void App1::MainPage::Image_Loaded(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
{
 auto img = dynamic_cast<Image^>(sender);
 if (img != nullptr)
 {
  auto bitmapImage = ref new BitmapImage();
  img->Width = 280; bitmapImage->DecodePixelWidth = 280;
  bitmapImage->UriSource = ref new Uri("ms-appx:///Assets/Logo.png");
  img->Source = bitmapImage;
 }
}

如果检索或解码图像源存在任何计时问题,则可以处理 ImageOpened 事件,在图像源可用之前,可能需要显示备用内容。 有关示例代码 ,请参阅 XAML 图像示例 。

在代码中使用相对 URI

我们之前看到,XAML 分析器使用正在分析的 XAML 页面的基本统一资源标识符(URI)解释相对统一资源标识符(URI)。 若要在代码中实现相同的结果,可以使用创建统一资源标识符(URI)的构造函数之一构造 URI ,方法是组合绝对基和该位置内的相对路径。 对于第一个参数,在加载图像的 Page 上调用 BaseUri。 (还可以在设置源的 Image 实例上调用 BaseUri,或者在页面上调用另一个元素。请参阅下面的警告。这会使用 ms-appx:方案创建统一资源标识符(URI),并添加作为 XAML 页面位置一部分的路径。 对于第二个参数,传递描述源图像位置的相对统一资源标识符(URI)字符串。

在 C# 中, URI 类型投影为 System.Uri,因此请使用将字符串作为第二个参数的 System.Uri(Uri、String) 构造函数。 在 C++ 中,使用 Uri(字符串,字符串)。

<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;
auto bitmapImage = ref new Windows::UI::Xaml::Media::Imaging::BitmapImage();
// Call BaseUri on the root Page element and combine it with a relative path
// to consruct an absolute URI.
bitmapImage->UriSource = ref new Windows::Foundation::Uri(BaseUri->AbsoluteUri, "Assets/placeholder.png");
capturedPhoto->Source = bitmapImage;

注释

如果在代码中实例化新的 Image , 则 BaseUri 属性为 null ,直到 图像 添加到页面的可视化树。 例如,以下代码引发 ArgumentNull 异常。 若要避免出现异常,请在设置 Source 属性之前将 图像 添加到可视化树。

此示例引发异常,因为它在将 Image 添加到页面之前调用 Image 上的 BaseUri。 假定“stackPanel1”是 XAML 中声明的 StackPanel 元素。

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);
auto img = ref new Image();
auto bitmapImage = ref new Windows::UI::Xaml::Media::Imaging::BitmapImage();

// AN EXCEPTION IS THROWN BECAUSE img->BaseUri IS NULL AT THIS POINT.
auto uri = ref new Windows::Foundation::Uri(img->BaseUri->AbsoluteUri, "Assets/Logo.png");

bitmapImage->UriSource = uri;
img->Source = bitmapImage;
stackPanel1->Children->Append(img);

若要避免此错误,可以在 Page 本身上调用 BaseUri,如前所示,或在调用 BaseUri 之前将图像添加到页面,如下所示。

在此示例中,映像将添加到对 BaseUri 的调用之前的页面,因此 BaseUri 不为 null。 假定“stackPanel1”是 XAML 中声明的 StackPanel 元素。

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;
auto img = ref new Image();
// Add the image to the page.
stackPanel1->Children->Append(img);

auto bitmapImage = ref new Windows::UI::Xaml::Media::Imaging::BitmapImage();
// img->BaseUri in not null because img has been added to the page.
auto uri = ref new Windows::Foundation::Uri(img->BaseUri->AbsoluteUri, "Assets/Logo.png");
bitmapImage->UriSource = uri;
img->Source = bitmapImage;

使用来自网络的文件

若要将网络位置中的文件用作图像源,请使用 http: 或 https: 方案,如下所示。 指定绝对统一资源标识符(URI)。 有关详细信息,请参阅 如何加载文件资源。

<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"));
auto img = ref new Image();
img->Source = ref new BitmapImage(ref new Windows::Foundation::Uri("http://www.contoso.com/images/logo.png"));

使用本地存储中的文件

若要将放置在应用的本地存储中的文件用作图像源,请使用 ms-appdata: 方案,如下所示。 指定绝对统一资源标识符(URI)。 有关详细信息,请参阅 如何加载文件资源。

<!-- 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;

使用流源显示图片库中的图像

应用中 图像 元素的典型用法是显示用户图片库中的图片。 可以通过编程方式或通过 FileOpenPicker 访问这些图片。 无论哪种情况,都可以将获取的 StorageFile 对象作为流打开,但不提供对映像文件的统一资源标识符(URI)引用。 若要将流用作图像源,必须编写用于设置 图像 实例以使用该流的代码。 这不能单独在 XAML 中完成。

若要显示单个图像,请使用来自枚举库的 StorageFile 对象并调用 OpenAsync 来获取流。 使用此流可以设置图像源,方法是创建新的 BitmapImage,然后调用 SetSourceAsync 并传递要用作 streamSource 参数的流。

此示例演示如何使用 FileOpenPicker 从图片库访问图像文件,并将其设置为 图像 控件的源。 代码已可等待,因为它正在等待用户选择文件,并且仅在发生该文件后运行。 要使用的流来自 StorageFile.OpenAsync 后,从异步选取器操作返回 StorageFile 实例。 有关使用文件选取器的详细信息,请参阅 使用选取器打开文件和文件夹。

<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;
        }
    }
}

此示例演示如何以编程方式从图片库访问图像文件,并将其设置为 图像 控件的源。 若要以编程方式访问图片库的内容,请调用 StorageFolder.GetFilesAsync。 请记住,你需要指定以编程方式访问图片库的功能。

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);
            }
        }
    }
}

图像源和缩放

如果要引用应用中打包的图像,则应以多个建议的大小创建映像源,以确保应用在缩放Windows 运行时时看起来很棒。 将 映像 的源指定为统一资源标识符(URI)时,可以使用命名约定,该约定将在运行时自动引用当前缩放的正确映像资源,如系统在运行时检测到的那样。 有关命名约定的详细信息,请参阅 快速入门:使用文件或映像资源。

有关如何进行缩放设计的详细信息,请参阅图像中的响应式设计 101 或备注。

图像源和资源限定符

可以使用自动处理来访问具有当前规模和区域性限定符的不合格资源,或者可以将 ResourceManager 和 ResourceMap 与区域性和规模限定符配合使用,以便直接获取资源。 有关详细信息,请参阅映像中的资源管理系统或备注。 有关应用资源以及如何在应用中打包图像源的详细信息,请参阅 定义应用资源。

适用于

另请参阅