Dela via


BitmapImage Class

Definition

Provides the practical object source type for the Image.Source and ImageBrush.ImageSource properties. You can define a BitmapImage by using a Uniform Resource Identifier (URI) that references an image source file, or by calling SetSourceAsync and supplying a stream.

public ref class BitmapImage sealed : BitmapSource
/// [Windows.Foundation.Metadata.Activatable(Windows.UI.Xaml.Media.Imaging.IBitmapImageFactory, 65536, Windows.Foundation.UniversalApiContract)]
/// [Windows.Foundation.Metadata.Activatable(65536, Windows.Foundation.UniversalApiContract)]
/// [Windows.Foundation.Metadata.ContractVersion(Windows.Foundation.UniversalApiContract, 65536)]
/// [Windows.Foundation.Metadata.MarshalingBehavior(Windows.Foundation.Metadata.MarshalingType.Agile)]
/// [Windows.Foundation.Metadata.Threading(Windows.Foundation.Metadata.ThreadingModel.Both)]
class BitmapImage final : BitmapSource
/// [Windows.Foundation.Metadata.ContractVersion(Windows.Foundation.UniversalApiContract, 65536)]
/// [Windows.Foundation.Metadata.MarshalingBehavior(Windows.Foundation.Metadata.MarshalingType.Agile)]
/// [Windows.Foundation.Metadata.Threading(Windows.Foundation.Metadata.ThreadingModel.Both)]
/// [Windows.Foundation.Metadata.Activatable(Windows.UI.Xaml.Media.Imaging.IBitmapImageFactory, 65536, "Windows.Foundation.UniversalApiContract")]
/// [Windows.Foundation.Metadata.Activatable(65536, "Windows.Foundation.UniversalApiContract")]
class BitmapImage final : BitmapSource
[Windows.Foundation.Metadata.Activatable(typeof(Windows.UI.Xaml.Media.Imaging.IBitmapImageFactory), 65536, typeof(Windows.Foundation.UniversalApiContract))]
[Windows.Foundation.Metadata.Activatable(65536, typeof(Windows.Foundation.UniversalApiContract))]
[Windows.Foundation.Metadata.ContractVersion(typeof(Windows.Foundation.UniversalApiContract), 65536)]
[Windows.Foundation.Metadata.MarshalingBehavior(Windows.Foundation.Metadata.MarshalingType.Agile)]
[Windows.Foundation.Metadata.Threading(Windows.Foundation.Metadata.ThreadingModel.Both)]
public sealed class BitmapImage : BitmapSource
[Windows.Foundation.Metadata.ContractVersion(typeof(Windows.Foundation.UniversalApiContract), 65536)]
[Windows.Foundation.Metadata.MarshalingBehavior(Windows.Foundation.Metadata.MarshalingType.Agile)]
[Windows.Foundation.Metadata.Threading(Windows.Foundation.Metadata.ThreadingModel.Both)]
[Windows.Foundation.Metadata.Activatable(typeof(Windows.UI.Xaml.Media.Imaging.IBitmapImageFactory), 65536, "Windows.Foundation.UniversalApiContract")]
[Windows.Foundation.Metadata.Activatable(65536, "Windows.Foundation.UniversalApiContract")]
public sealed class BitmapImage : BitmapSource
Public NotInheritable Class BitmapImage
Inherits BitmapSource
<BitmapImage .../>
Inheritance
Object Platform::Object IInspectable DependencyObject ImageSource BitmapSource BitmapImage
Attributes

Windows requirements

Device family
Windows 10 (introduced in 10.0.10240.0)
API contract
Windows.Foundation.UniversalApiContract (introduced in v1.0)

Examples

Here's an example of using a BitmapImage object to set Image.Source in C#. 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; 
    BitmapImage bitmapImage = new BitmapImage();
    img.Width = bitmapImage.DecodePixelWidth = 80; 
    // Natural px width of image source.
    // You don't need to set Height; the system maintains aspect ratio, and calculates the other
    // dimension, as long as one dimension measurement is provided.
    bitmapImage.UriSource = new Uri(img.BaseUri,"Assets/StoreLogo.png");
    img.Source = bitmapImage;
}

Remarks

A BitmapImage can be sourced from these image file formats:

  • Joint Photographic Experts Group (JPEG)
  • Portable Network Graphics (PNG)
  • bitmap (BMP)
  • Graphics Interchange Format (GIF)
  • Tagged Image File Format (TIFF)
  • JPEG XR
  • icons (ICO)

If the image source is a stream, that stream is expected to contain an image file in one of these formats.

The BitmapImage class represents an abstraction so that an image source can be set asynchronously but still be referenced in XAML markup as a property value, or in code as an object that doesn't use awaitable syntax. When you create a BitmapImage object in code, it initially has no valid source. You should then set its source using one of these techniques:

  • Use the BitmapImage(Uri) constructor rather than the default constructor. Although it's a constructor you can think of this as having an implicit asynchronous behavior: the BitmapImage won't be ready for use until it raises an ImageOpened event that indicates a successful async source set operation.
  • Set the UriSource property. As with using the Uri constructor, this action is implicitly asynchronous, and the BitmapImage won't be ready for use until it raises an ImageOpened event.
  • Use SetSourceAsync. This method is explicitly asynchronous. The properties where you might use a BitmapImage, such as Image.Source, are designed for this asynchronous behavior, and won't throw exceptions if they are set using a BitmapImage that doesn't have a complete source yet. Rather than handling exceptions, you should handle ImageOpened or ImageFailed events either on the BitmapImage directly or on the control that uses the source (if those events are available on the control class).

ImageFailed and ImageOpened are mutually exclusive. One event or the other will always be raised whenever a BitmapImage object has its source value set or reset.

BitmapImage and encoding

The underlying codec support for image files is supplied by Windows Imaging Component (WIC) API in Windows. For more info on specific image formats as documented for the codecs, see Native WIC Codecs. For more info on formats and how to use Uniform Resource Identifier (URI) to access image source files that come from app resources, see Image and ImageBrush.

The API for Image, BitmapImage and BitmapSource doesn't include any dedicated methods for encoding and decoding of media formats. All of the encode and decode operations are built-in, and at most will surface aspects of encode or decode as part of event data for load events. If you want to do any special work with image encode or decode, which you might use if your app is doing image conversions or manipulation, you should use the API that are available in the Windows.Graphics.Imaging namespace. These imaging API can be used by either UWP app using C++, C#, or Visual Basic or Windows app using JavaScript. These APIs are also supported by the Windows Imaging Component (WIC) component of Windows 8.

Animated images

Starting in Windows 10, version 1607, the XAML Image element supports animated GIF images. When you use a BitmapImage as the image Source, you can access BitmapImage API to control playback of the animated GIF image.

  • Use the AutoPlay property, which defaults to true, to specify whether or not an animated bitmap plays as soon as it loads.
  • Use the IsAnimatedBitmap property to check whether a bitmap is animated.
  • Use the IsPlaying property along with the Play and Stop methods to control the playback of an animated bitmap.

Note

For most apps, we recommend that you set AutoPlay to false if UISettings.AnimationsEnabled is false, to support the accessibility needs of users. Do not do this if the content of the animated GIF is important for the usability of your app.

If your app runs on releases of Windows 10 prior to version 1607, you must use the ApiInformation class to check for the presence of these members before you use them. For more info, see Version adaptive code: Use new APIs while maintaining compatibility with previous versions.

This example shows how to use an animated GIF. A button lets the user start or stop the animation. This example uses version adaptive code so it can run on all versions of Windows 10. On versions prior to version 1607, the first frame of the GIF is shown, but it is not animated.

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <Image Loaded="Image_Loaded">
        <Image.Source>
            <BitmapImage x:Name="imageSource"
                         UriSource="Assets/example.gif"
                         ImageOpened="imageSource_ImageOpened"/>
        </Image.Source>
    </Image>

    <AppBarButton x:Name="playButton"
              Icon="Play"
              Visibility="Collapsed"
              Click="playButton_Click"/>
</Grid>
// Set the AutoPlay property.
private void Image_Loaded(object sender, RoutedEventArgs e)
{
    if (ApiInformation.IsPropertyPresent("Windows.UI.Xaml.Media.Imaging.BitmapImage", "AutoPlay") == true)
    {
        imageSource.AutoPlay = false;
    }
}

// Show the play/stop button if the image is animated.
private void imageSource_ImageOpened(object sender, RoutedEventArgs e)
{
    var bitmapImage = (BitmapImage)sender;
    // At this point you can query whether the image is animated or not.
    if (ApiInformation.IsPropertyPresent("Windows.UI.Xaml.Media.Imaging.BitmapImage", "IsAnimatedBitmap") 
        && bitmapImage.IsAnimatedBitmap == true)
    {
        // Enable the play button
        playButton.Visibility = Visibility.Visible;
    }
}

// Play or stop the animated bitmap.
void playButton_Click(object sender, RoutedEventArgs e)
{
    if (ApiInformation.IsPropertyPresent("Windows.UI.Xaml.Media.Imaging.BitmapImage", "IsPlaying"))
    {
        // You can call the Play and Stop methods safely because is the IsPlaying property is
        // present, these methods are also present.
        if (imageSource.IsPlaying == true)
        {
            playButton.Icon = new SymbolIcon(Symbol.Play);
            imageSource.Stop();
        }
        else
        {
            playButton.Icon = new SymbolIcon(Symbol.Stop);
            imageSource.Play();
        }
    }
}

For more examples, see the Animated GIF playback sample.

Version history

Windows version SDK version Value added
1607 14393 AutoPlay
1607 14393 IsAnimatedBitmap
1607 14393 IsPlaying
1607 14393 Play
1607 14393 Stop

Constructors

BitmapImage()

Initializes a new instance of the BitmapImage class.

BitmapImage(Uri)

Initializes a new instance of the BitmapImage class, using the supplied Uniform Resource Identifier (URI).

Properties

AutoPlay

Gets or sets a value that indicates whether an animated image should play as soon as it loads.

AutoPlayProperty

Identifies the AutoPlay dependency property.

CreateOptions

Gets or sets the BitmapCreateOptions for a BitmapImage.

CreateOptionsProperty

Identifies the CreateOptions dependency property.

DecodePixelHeight

Gets or sets the height to use for image decoding operations.

DecodePixelHeightProperty

Identifies the DecodePixelHeight dependency property.

DecodePixelType

Gets or sets a value that determines how DecodePixelWidth and DecodePixelHeight values are interpreted for decoding operations.

DecodePixelTypeProperty

Identifies the DecodePixelType dependency property.

DecodePixelWidth

Gets or sets the width to use for image decoding operations.

DecodePixelWidthProperty

Identifies the DecodePixelWidth dependency property.

Dispatcher

Gets the CoreDispatcher that this object is associated with. The CoreDispatcher represents a facility that can access the DependencyObject on the UI thread even if the code is initiated by a non-UI thread.

(Inherited from DependencyObject)
IsAnimatedBitmap

Gets a value that indicates whether an image is animated.

IsAnimatedBitmapProperty

Identifies the IsAnimatedBitmap dependency property.

IsPlaying

Gets a value that indicates whether an animated image is playing.

IsPlayingProperty

Identifies the IsPlaying dependency property.

PixelHeight

Gets the height of the bitmap in pixels.

(Inherited from BitmapSource)
PixelWidth

Gets the width of the bitmap in pixels.

(Inherited from BitmapSource)
UriSource

Gets or sets the Uniform Resource Identifier (URI) of the graphics source file that generated this BitmapImage.

UriSourceProperty

Identifies the UriSource dependency property.

Methods

ClearValue(DependencyProperty)

Clears the local value of a dependency property.

(Inherited from DependencyObject)
GetAnimationBaseValue(DependencyProperty)

Returns any base value established for a dependency property, which would apply in cases where an animation is not active.

(Inherited from DependencyObject)
GetValue(DependencyProperty)

Returns the current effective value of a dependency property from a DependencyObject.

(Inherited from DependencyObject)
Play()

Starts the animation of an animated image.

ReadLocalValue(DependencyProperty)

Returns the local value of a dependency property, if a local value is set.

(Inherited from DependencyObject)
RegisterPropertyChangedCallback(DependencyProperty, DependencyPropertyChangedCallback)

Registers a notification function for listening to changes to a specific DependencyProperty on this DependencyObject instance.

(Inherited from DependencyObject)
SetSource(IRandomAccessStream)

Sets the source image for a BitmapSource by accessing a stream. Most callers should use SetSourceAsync instead.

(Inherited from BitmapSource)
SetSourceAsync(IRandomAccessStream)

Sets the source image for a BitmapSource by accessing a stream and processing the result asynchronously.

(Inherited from BitmapSource)
SetValue(DependencyProperty, Object)

Sets the local value of a dependency property on a DependencyObject.

(Inherited from DependencyObject)
Stop()

Ends the animation of an animated image.

UnregisterPropertyChangedCallback(DependencyProperty, Int64)

Cancels a change notification that was previously registered by calling RegisterPropertyChangedCallback.

(Inherited from DependencyObject)

Events

DownloadProgress

Occurs when a significant change has occurred in the download progress of the BitmapImage content.

ImageFailed

Occurs when there is an error associated with image retrieval or format.

ImageOpened

Occurs when the image source is downloaded and decoded with no failure. You can use this event to determine the size of an image before rendering it.

Applies to

See also