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"/>

속성 값

그린 이미지의 이미지 원본 파일을 나타내는 개체입니다. 일반적으로 유효한 이미지 원본 파일의 경로를 설명하는 URI(Uniform Resource Identifier)로 생성된 BitmapImage 개체를 사용하여 설정합니다. 또는 스토리지 파일의 스트림과 같은 스트림을 사용하여 BitmapSource 를 초기화할 수 있습니다.

설명

Source 속성을 설정하는 것은 기본적으로 비동기 작업입니다. 속성이므로 대기 가능한 구문은 없지만 대부분의 시나리오에서는 이미지 원본 파일 로드의 비동기 측면과 상호 작용할 필요가 없습니다. 프레임워크는 이미지 원본이 반환될 때까지 대기하고 이미지 원본 파일을 사용할 수 있게 되면 레이아웃을 다시 실행합니다.

원본을 유효한 이미지 원본 파일로 확인할 수 없는 URI(Uniform Resource Identifier) 값으로 설정해도 예외가 발생하지 않습니다. 대신 ImageFailed 이벤트를 실행합니다. 디코딩 실패로 ImageFailed도 발생합니다. ImageFailed 처리기를 작성하고 Image 개체에 연결하여 이를 감지하고 이벤트 데이터에서 ErrorMessage를 사용하여 오류의 특성을 확인할 수 있습니다. 또한 이미지 원본 파일이 올바르게 로드되었는지 확인하려는 경우 Image 요소에서 ImageOpened 이벤트를 처리할 수 있습니다.

XAML에서 원본 설정

XAML에서 Source 속성을 특성으로 설정할 수 있습니다. 이 경우 원본 특성 값을 원본 이미지 파일의 위치를 설명하는 URI(Uniform Resource Identifier) 문자열로 설정합니다. 이 동작은 문자열을 URI(Uniform Resource Identifier)로 처리하고 BitmapImage(Uri) 생성자에 해당하는 를 호출하는 기본 형식 변환을 사용합니다. URI(Uniform Resource Identifier) 문자열을 사용하여 Source 속성을 설정하는 것은 XAML에서 사용하는 바로 가기입니다. 여기서 URI(Uniform Resource Identifier)는 상대적인 URI(Uniform Resource Identifier)로 표시됩니다. 부분적인 URI(Uniform Resource Identifier)를 지원하는 것은 또 다른 XAML 바로 가기입니다.

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

XAML 파서는 구문 분석 중인 XAML 페이지의 기본 URI(Uniform Resource Identifier)를 사용하여 상대 URI(Uniform Resource Identifier)를 나타내는 모든 문자열을 해석합니다. 예를 들어 XAML에서 "Images/myImage.png" 값을 지정하는 경우 해당 문자열은 XAML 페이지 자체가 있는 앱 패키지 내의 기본 URI(Uniform Resource Identifier) 위치에 추가되는 상대 경로 접미사로 해석됩니다. 이전 Image 요소가 앱 패키지의 루트에 있는 페이지에 추가되면 URI(Uniform Resource Identifier)가 ms-appx:///Images/myImage.png 해석됩니다. 이미지가 앱의 Pages 폴더에 있는 페이지에 추가되면 URI(Uniform Resource Identifier)가 ms-appx:///Pages/Images/myImage.png 해석됩니다.

원본 이미지가 앱 패키지의 일부가 아닌 경우 절대 URI(Uniform Resource Identifier)를 사용하여 XAML에서 Source 속성을 설정해야 합니다. 자세한 내용은 파일 리소스를 로드하는 방법 및 이 문서의 뒷부분에 있는 예제를 참조하세요.

XAML의 속성 요소 구문도 가능하며, 유효한 소스가 있는 BitmapImage 개체 요소를 속성 값으로 지정합니다.

코드에서 소스 설정

코드에서 Image.Source 속성을 설정하려면 구성해야 하는 BitmapImage(또는 BitmapSource)의 instance 필요합니다. 이미지 원본이 스트림인 경우 BitmapImage의 비동기 SetSourceAsync 메서드를 사용하여 스트림의 이미지 정보를 정의합니다.

이미지 원본이 URI(Uniform Resource Identifier)에서 참조하는 파일인 경우 BitmapImage.UriSource 속성을 설정하거나 URI(Uniform Resource Identifier) 매개 변수를 사용하는 BitmapImage 생성자를 사용합니다. Windows 런타임 URI(Uniform Resource Identifier)가 절대적이어야 하며, Windows 런타임 코드에서는 상대 URI(Uniform Resource Identifier)를 사용할 수 없습니다. .NET Framework System.Uri 값을 사용하고 UriKind 값이 필요한 서명을 사용하는 경우 Absolute를 지정해야 합니다.

로컬 콘텐츠를 참조할 때 BitmapImage.UriSource로 사용하는 절대 URI(Uniform Resource Identifier)에 ms-appx: 체계를 포함해야 합니다. 코드에서는 원본을 XAML 특성으로 지정하면 자동으로 발생하는 상대 URI(Uniform Resource Identifier) 부분과 ms-appx: 체계를 결합하기 위한 처리 바로 가기를 얻지 못합니다. 대신 적절한 체계를 사용하여 절대 URI(Uniform Resource Identifier)를 명시적으로 생성해야 합니다.

앱 패키지에서 원본을 이미지로 설정하는 방법은 다음과 같습니다.

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 속성을 설정합니다.

참고

FrameworkElement.Loaded 이벤트는 이미지 컨트롤이 XAML 페이지에 로드될 때 발생합니다. 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(Uniform Resource Identifier)를 사용하여 상대 URI(Uniform Resource Identifier)를 해석하는 것을 보았습니다. 코드에서 동일한 결과를 얻으려면 절대 기준과 해당 위치 내의 상대 경로를 결합하여 URI(Uniform Resource Identifier)를 만드는 생성자 중 하나를 사용하여 Uri 를 생성할 수 있습니다. 첫 번째 매개 변수의 경우 이미지가 로드되는 페이지에서BaseUri를 호출합니다. (원본을 설정하는 이미지 instance 또는 페이지의 다른 요소에서 BaseUri를 호출할 수도 있습니다. 아래의 주의 사항을 참조하세요.) ms-appx: 체계를 사용하여 URI(Uniform Resource Identifier)를 만들고 XAML 페이지 위치의 일부인 경로를 추가합니다. 두 번째 매개 변수의 경우 원본 이미지 위치를 설명하는 상대 URI(Uniform Resource Identifier) 문자열을 전달합니다.

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 = winrt::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(winrt::Windows::Foundation::Uri(BaseUri().AbsoluteUri(), L"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 예외를 throw합니다. 예외를 방지하려면 Source 속성을 설정하기 전에 시각적 트리에 이미지를 추가합니다.

다음은 이미지가 페이지에 추가되기 전에 이미지에서 BaseUri를 호출하기 때문에 예외를 throw하는 예제입니다. '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);
Image img;
BitmapImage bitmapImage;

// AN EXCEPTION IS THROWN BECAUSE img.BaseUri IS NULL AT THIS POINT.
Uri uri(img.BaseUri(), L"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를 호출하기 전에 이미지가 페이지에 추가되므로 BaseUrinull 아닙니다. '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;
Image img;
// Add the image to the page.
stackPanel1.Children().Add(img);

BitmapImage bitmapImage;
// img.BaseUri in not null because img has been added to the page.
Uri uri(img.BaseUri(), L"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(Uniform Resource Identifier)를 지정합니다. 자세한 내용은 파일 리소스를 로드하는 방법을 참조하세요.

<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"));
Image img;
img.Source(BitmapImage(Uri(L"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(Uniform Resource Identifier)를 지정합니다. 자세한 내용은 파일 리소스를 로드하는 방법을 참조하세요.

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

스트림 원본을 사용하여 사진 라이브러리의 이미지 표시

앱에서 Image 요소를 일반적으로 사용하는 것은 사용자의 사진 라이브러리에서 그림을 표시하는 것입니다. 이러한 그림은 프로그래밍 방식으로 또는 FileOpenPicker를 통해 액세스할 수 있습니다. 두 경우 모두 가져오는 StorageFile 개체를 스트림으로 열 수 있지만 이미지 파일에 대한 URI(Uniform Resource Identifier) 참조는 제공하지 않습니다. 스트림을 이미지 원본으로 사용하려면 스트림을 사용하도록 Image instance 설정하는 코드를 작성해야 합니다. 이 작업은 XAML에서만 수행할 수 없습니다.

개별 이미지를 표시하려면 라이브러리 열거에서 StorageFile 개체를 사용하고 OpenAsync 를 호출하여 스트림을 가져옵니다. 이 스트림을 사용하여 새 BitmapImage를 만든 다음 SetSourceAsync 를 호출하고 streamSource 매개 변수로 사용할 스트림을 전달하여 이미지 원본을 설정합니다.

이 예제에서는 FileOpenPicker 를 사용하여 사진 라이브러리에서 이미지 파일에 액세스하고 이미지 컨트롤의 원본으로 설정하는 방법을 보여 있습니다. 이 코드는 사용자가 파일을 선택할 때까지 대기하고 해당 이후에만 실행되므로 이미 대기할 수 있습니다. 사용할 스트림은 StorageFile instance 비동기 선택기 작업에서 반환된 후 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(Uniform Resource Identifier)로 지정할 때 런타임에 시스템에서 감지한 대로 현재 크기 조정에 대한 올바른 이미지 리소스를 자동으로 참조하는 명명 규칙을 사용할 수 있습니다. 명명 규칙의 특성 및 자세한 내용은 빠른 시작: 파일 또는 이미지 리소스 사용을 참조하세요.

크기 조정을 위해 디자인하는 방법에 대한 자세한 내용은 화면 크기 및 중단점 또는 이미지의 비고를 참조 하세요.

이미지 원본 및 리소스 한정자

현재 크기 조정 및 문화권 한정자를 사용하여 정규화되지 않은 리소스에 액세스하기 위해 자동 처리를 사용하거나, Culture 및 scale에 대한 한정 자와 함께 ResourceManagerResourceMap 을 사용하여 리소스를 직접 가져올 수 있습니다. 자세한 내용은 이미지의 리소스 관리 시스템 또는 비고를 참조 하세요. 앱 리소스 및 앱에서 이미지 원본을 패키지하는 방법에 대한 자세한 내용은 앱 리소스 정의를 참조하세요.

적용 대상

추가 정보