Image.Source 屬性
定義
重要
部分資訊涉及發行前產品,在發行之前可能會有大幅修改。 Microsoft 對此處提供的資訊,不做任何明確或隱含的瑕疵擔保。
取得或設定影像的來源。
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 來判斷故障的性質。 另外,如果你想驗證影像來源檔是否正確載入,可以在影像元素上處理 ImageOpened 事件。
XAML 中的設定原始碼
你可以在 XAML 裡把 Source 屬性設為屬性。 在此情況下,你將 Source 屬性值設定為統一資源識別碼(URI)字串,描述來源影像檔案的位置。 此行為依賴底層型別轉換,將字串處理為統一資源識別碼(URI),並呼叫相當於 BitmapImage(Uri) 建構子的結構。 使用 Uniform Resource Identifier(URI)字串設定 Source 屬性是 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 中的原始碼屬性。 更多資訊請參見本文件後面的 「如何載入檔案資源」及範例。
XAML 中也可以使用屬性元素語法,指定一個具有有效來源的 BitmapImage 物件元素作為屬性值。
程式碼中的設定原始碼
要在程式碼中設定 Image.Source 屬性,需要一個 BitmapImage (或 BitmapSource)實例,且你也必須建構它。 如果你的影像來源是串流,請使用 BitmapImage 的非同步 SetSourceAsync 方法來定義串流中的影像資訊。
如果你的影像來源是由統一資源識別碼(URI)參考的檔案,請設定 BitmapImage.UriSource 屬性,或使用採用統一資源識別碼(URI)參數的 BitmapImage 建構器。 Windows 執行階段 強制統一資源識別碼(URI)必須是絕對的;在 Windows 執行階段 程式碼中,你不能使用相對的統一資源識別碼(URI)。 如果你使用的是 .NET Framework System.Uri 值,且簽章需要 UriKind 值,請務必指定 Absolute。
當你引用本地內容時,必須在你作為 BitmapImage.UriSource 使用的絕對統一資源識別碼(URI)中包含 ms-appx: scheme。 在程式碼中,你不會有將相對的統一資源識別碼(URI)部分合併的處理捷徑,以及如果你指定 Source 為 XAML 屬性時會自動發生的 ms-appx: 方案。 相反地,你必須明確構建一個絕對統一資源識別碼(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 屬性。
Note
當 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)。 對於第一個參數,請在載入圖片的頁面呼叫 BaseUri。 (你也可以在設定來源的 Image 實例中呼叫 BaseUri,或在頁面上呼叫其他元素。詳見下方的警告。)此系統建立一個統一資源識別碼(URI),使用 ms-appx: 方案,並加入 XAML 頁面位置的路徑。 第二個參數則傳遞描述來源影像位置的相對統一資源識別碼(URI)字串。
在 C# 中, Uri 型態投影為 System.Uri,因此請使用 System.Uri(Uri, String) 建構子,該建構子將字串作為第二個參數。 在 C++ 中,使用 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;
Note
如果你在程式碼中實例化一個新的 影像 , BaseUri 屬性會是 空 的,直到該 影像 被加入頁面的視覺樹。 例如,以下程式碼拋出 一個 ArgumentNull 例外。 為避免例外,請先將 影像 加入視覺樹,再設定來源屬性。
此範例會拋出例外,因為它在圖片加入頁面前就呼叫了 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);
為避免此錯誤,你可以如前所述在頁面上呼叫 BaseUri,或在呼叫 BaseUri 前先將圖片加入頁面,如圖所示。
在此範例中, 圖片 會在呼叫 BaseUri 之前加入頁面,因此 BaseUri 並非 空。 假設 '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)時,您可以使用命名慣例,自動參考系統在執行時偵測到的當前縮放所需的正確影像資源。 有關命名慣例的詳細資料和更多資訊,請參閱快速入門:使用檔案或影像資源。
關於如何設計縮放的更多資訊,請參閱 響應式設計入門 或 圖片備註。
圖片來源與資源限定條件
你可以使用自動處理來存取帶有當前規模與文化限定條件的未合格資源,或使用 ResourceManager 和 ResourceMap 的文化與規模限定條件直接取得資源。 更多資訊請參閱 資源管理系統 或 圖片備註。 如需更多關於應用程式資源及如何在應用程式中打包影像來源的資訊,請參閱 「定義應用程式資源」。