共用方式為


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 中設定來源

您可以將Source屬性設定為 XAML 中的屬性。 在此情況下,您會將 [來源] 屬性值設定為統一資源標識碼 (URI) 字串,以描述來源圖像檔的位置。 此行為依賴基礎類型轉換,以統一資源識別元 (URI) 處理字串,並呼叫 位圖Image (Uri) 建構函式的對等專案。 使用統一資源識別碼設定來源屬性 (URI) 字串是 XAML 所啟用的快捷方式。 請注意,此處的統一資源標識符 (URI) 看起來是相對的統一資源標識碼 (URI) ;支援部分統一資源標識碼 (URI) 是另一個 XAML 快捷方式。

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

XAML 剖析器會使用所剖析之 XAML 頁面的基底統一資源識別碼 (URI) ,解譯代表相對統一資源識別元 () URI 的任何字元串。 例如,如果您在 XAML 中指定 「Images/myImage.png」 值,該字串會解譯為附加至基底統一資源識別元的相對路徑後綴, (URI) XAML 頁面本身所在的應用程式套件內的位置。 如果先前的 Image 元素新增至應用程式套件根目錄中的頁面,則會將統一資源識別元 (URI) 解譯為 ms-appx:///Images/myImage.png。 如果 影像 新增至應用程式中 Pages 資料夾中的頁面,則會將統一資源標識碼 (URI) 解譯為 ms-appx:///Pages/Images/myImage.png。

如果來源映像不是應用程式套件的一部分,您必須使用絕對統一資源標識碼 (URI) ,才能在 XAML 中設定 Source 屬性。 如需詳細資訊,請參閱 如何載入文件資源,以及本檔稍後的範例。

您也可以使用 XAML 中的屬性項目語法,將具有有效來源的 BitmapImage 物件專案指定為屬性值。

在程式代碼中設定原始程式碼

若要在程式代碼中設定 Image.Source 屬性,則需要 BitmapImage (實例或 BitmapSource) ,您也必須建構此屬性。 如果您的影像來源是數據流,請使用 BitmapImageasync SetSourceAsync 方法來定義數據流中的影像資訊。

如果您的影像來源是統一資源標識碼 (URI) 所參考的檔案,請設定 BitmapImage.UriSource 屬性,或使用採用統一資源標識碼 (URI) 參數的 BitmapImage 建構函式。 Windows 執行階段 會強制執行統一資源識別元 (URI) 必須是絕對的;您無法在 Windows 執行階段 程式代碼中使用相對統一資源標識碼 (URI) 。 如果您使用 .NET Framework System.Uri 值,而且您使用需要 UriKind 值的簽章,請務必指定 Absolute

當您參考本機內容時,您必須在絕對統一資源標識碼 (URI 中包含 ms-appx: 配置,) 您做為 BitmapImage.UriSource。 在程式代碼中,您不會取得將相對統一資源識別元 (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"));

如果您需要確保 Image 控制件已就緒,再嘗試在程式代碼中使用、處理 Loaded 事件,並在事件處理程式中設定 Source 屬性。

注意

Image 控制件載入 XAML 頁面時,就會發生 FrameworkElement.Loaded 事件。 ImageOpened 事件發生於映射控件中開啟映像檔時。

以下是在 Loaded 事件的處理程式中設定 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) 。 針對第一個參數,在載入 ImagePage 上呼叫 BaseUri。 (您也可以在設定來源的 Image 實例上呼叫 BaseUri,或在頁面上呼叫另一個專案。請參閱下列警告。) 這會使用 ms-appx: 配置建立統一資源標識碼 (URI) ,並新增屬於 XAML 頁面位置一部分的路徑。 針對第二個參數,傳遞相對統一資源識別元 (URI) 字串,以描述來源影像位置。

在 C# 或 Microsoft Visual Basic 中, Uri 類型會投影為 System.Uri,因此請使用 System.Uri (Uri、String) 建構函式,其採用字符串作為第二個參數。 在 Visual C++ 元件延伸模組中, (C++/CX) 使用 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;
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 ,直到 Image 新增至頁面的可視化樹狀結構為止。 例如,下列程式代碼會擲回 ArgumentNull 例外狀況。 若要避免例外狀況,請先將 Image 新增至可視化樹狀結構,再設定 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之前將Image新增至頁面,如下所示。

在此範例中, Image 會在呼叫 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) 映射檔的參考。 若要使用數據流作為影像來源,您必須撰寫程式代碼,以將 Image 實例設定為使用數據流。 這不能單獨在 XAML 中完成。

若要顯示個別影像,請使用 StorageFile 物件來列舉連結庫,並呼叫 OpenAsync 以取得數據流。 使用此數據流來設定影像來源,方法是建立新的 BitmapImage,然後呼叫 SetSourceAsync 並傳遞數據流作為 streamSource 參數。

此範例示範如何使用 FileOpenPicker 從圖片庫存取圖像檔,並將其設定為 影像 控件的來源。 程式代碼已經可等候,因為它正在等候使用者選擇檔案,而且只會在發生該檔案之後執行。 從異步選擇器動作傳回 StorageFile 實例之後,要使用的數據流來自 StorageFile.OpenAsync。 如需使用檔案選擇器的詳細資訊,請參閱使用 選擇器開啟檔案和資料夾

<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 for Image 中的。

影像來源和資源限定符

您可以使用自動處理來存取具有目前縮放比例和文化特性限定符的非限定資源,也可以使用 ResourceManagerResourceMap 搭配文化特性和規模限定符,直接取得資源。 如需詳細資訊,請參閱 資源管理系統映像中的。 如需應用程式資源以及如何封裝應用程式中映射來源的詳細資訊,請參閱 定義應用程式資源

適用於

另請參閱