Imaging

Microsoft Silverlight will reach end of support after October 2021. Learn more.

This overview provides an introduction to working with images (JPEG or PNG formats) in Silverlight.

This topic contains the following sections.

  • Creating an Image
  • URIs and Image.Source
  • Stretching an Image
  • Cropping an Image
  • Applying an OpacityMask
  • Painting with an Image (ImageBrush)
  • Zooming and Panning Images
  • WriteableBitmap
  • Related Topics

Creating an Image

To render an image, you can use either the Image or the ImageBrush object. The following example shows how to create an image in three different declaration techniques (XAML markup, or code declarations in either Visual C# or Visual Basic).

  <Image Source="myPicture.png" />
Image myImage = new Image();
myImage.Source = new BitmapImage(new Uri("myPicture.jpg", UriKind.RelativeOrAbsolute));
LayoutRoot.Children.Add(myImage);
Dim myImage As Image = New Image
myImage.Source = New BitmapImage(New Uri("myPicture.jpg", UriKind.RelativeOrAbsolute))
LayoutRoot.Children.Add(myImage)

In this example, the Source property is used to specify the location of the image you want to display.

You use the ImageBrush to use an image to paint an area that takes a brush. For example, ImageBrush can be used for the value of the Background property of a Canvas or InkPresenter. For more information on using ImageBrush, see Painting with an Image (ImageBrush) later in this topic.

URIs and Image.Source

You can set the Source directly, by one of the following URL schemes:

  • An absolute URL, for example, https://contoso.com/myPicture.jpg.

  • Relative to the referencing XAML file. In this case, specify the relative URL with no leading slash. For example, Source="myPicture.png" specifies an image file that is embedded within the assembly and in the same folder location as the XAML file. You can also traverse upwards in directory structure so long as the path can resolve within the XAP structure. For example, Source="../resources/myPicture.png" specifies an image file from a Resources folder that is peer to the folder location where the XAP has located its XAML file components.

  • Relative to the XAP file application root. In this case, specify the relative URL with a leading slash, which begins the path resolution at the XAP structure root. For example, Source="/resources/myPicture.png" specifies a source from a root-level resources directory that is defined in the XAP structure. This technique is recommended over the previous relative-URL technique because changes to XAP location of XAML files (such as moving XAML from page definitions into resource dictionaries) do not break references that are made relative to the XAP structure root. This technique is typically used for image sources that are placed into a XAP as a Content build action.

  • Specifying an assembly, and then referencing the component; token to enter the assembly structure at its conceptual root. This is the most robust way to specify a URL, because it can continue to resolve to an image target even if you refactor the XAML entirely out of an assembly (for example, if you move this piece of XAML into a satellite assembly for localization purposes). For example, Source="MySilverlightApp;component/myPicture.png" references an assembly MySilverlightApp that should be available as a downloaded assembly. The assembly you specify can be the primary application assembly in the XAP, in other words the same assembly name as declared by the Silverlight project output path. Do not specify the .dll extension suffix in this URI scheme.

Some of the previously listed URI schemes have fallbacks. For more information on accessing resources by URI in Silverlight, see Resource Files.

Another technique for specifying an image source is to set the source asynchronously in code. For more information, see SetSource.

Stretching an Image

If you do not set a Width or Height value of an Image (as in the previous example), it is displayed with the natural dimensions of the image specified by the Source. Setting the Height and Width creates a containing rectangular area that the image is displayed in. You can specify how the image fills this containing area by using the Stretch property. The Stretch property accepts the following values, which the Stretch enumeration defines:

  • None: The image does not stretch to fill the output dimensions.

  • Uniform: The image is scaled to fit the output dimensions. However, the aspect ratio of the content is preserved. This is the default value.

  • UniformToFill: The image is scaled so that it completely fills the output area but preserves its original aspect ratio.

  • Fill: The video is scaled to fit the output dimensions. Because the content's height and width are scaled independently, the original aspect ratio of the image might not be preserved. That is, the image might be distorted to completely fill the output area.

The following illustration shows the different Stretch settings.

Stretch settings

Stretch values.

The following example displays an Image that fills a 300-by-300-pixel output area but preserves its original aspect ratio, because the Stretch property is set to UniformToFill.

<Canvas Width="300" Height="300" Background="Gray">
  
  <Image Source="myImage.jpg" Stretch="UniformToFill" Width="300" Height="300" />

</Canvas>
NoteNote:

When only one constraint attribute is set (for example, Height), the other attribute (in this case, Width) is automatically calculated based on the aspect ratio of the natural image. Because of this behavior, setting the Stretch property does not change the behavior unless it is set to None.

Cropping an Image

You can crop an image by using the Clip property to clip out an area of the image's output. You set the Clip property to a Geometry, which means that you can clip out a variety of geometric shapes from your image (for example, ellipse, line, or complex path). For more information about creating geometries, see Geometries.

The following example shows how to use an EllipseGeometry as the clip region for an image. In this example, an Image object is defined with a Width of 200 and a Height of 150. An EllipseGeometry with a RadiusX value of 100, a RadiusY value of 75, and a Center value of 100,75 is set to the Clip property of the image. Only the part of the image that is within the area of the ellipse is displayed.

<Grid x:Name="LayoutRoot" Background="White">
  <Image Source="Water_lilies.jpg"
    Width="200" Height="150">
    <Image.Clip>
      <EllipseGeometry RadiusX="100" RadiusY="75" Center="100,75"/>
    </Image.Clip>
  </Image>
</Grid>

The following illustration shows the output from the example.

An EllipseGeometry used to clip an image

Picture of licorice.

NoteNote:

A variety of objects can be clipped besides Image. For more information, see How to: Crop an Object.

NoteNote:

An alternative way to create a cropping effect is to apply an OpacityMask by using a gradient. In this case, because you are using Opacity, you are able to create a blurry edge to your cropping. For more information, see OpacityMask.

Applying an OpacityMask

You can apply an OpacityMask to an image to create a variety of opacity-related photo masking techniques such as vignette effects, as shown in the following illustration. For more information, see OpacityMask.

Example of a vignette effect created by an OpacityMask

Image with an OpacityMask applied to it.

Painting with an Image (ImageBrush)

You use ImageBrush to use an image to paint an area that takes a brush. For example, ImageBrush can be used for the value of the Background property of a Canvas or InkPresenter. For more information about brushes, see Brushes.

The following XAML example shows how to set the Foreground property to an ImageBrush whose image is used as the fill for the rendered text of the TextBlock.

<!-- TextBlock with an image brush applied to the text. -->
<TextBlock FontFamily="Verdana" FontSize="72"
 FontStyle="Italic" FontWeight="Bold">
    SHRUBBERY
  <TextBlock.Foreground>
    <ImageBrush ImageSource="forest.jpg"/>
  </TextBlock.Foreground>
</TextBlock>

The following illustration shows the results of this XAML example.

An ImageBrush used to fill text

Output from an ImageBrush.

Zooming and Panning Images

You can use a technology called Deep Zoom to enable zooming into and panning across large images or collections of high-resolution images.

An example of the use of Deep Zoom is the Hard Rock Memorabilia site. You can use the mouse wheel to zoom in and out and move around the images by dragging.

Normally, loading large images is not an optimal experience for users because of the lag required for the images to load. Deep Zoom mitigates this difficulty by loading progressively higher resolution images. This creates a "blurry to crisp" experience for users. In addition, Deep Zoom provides functionality to allow users to change their view of an image, using spring animations that give users the impression of a smooth "movement" around the image(s). The following are example of the use of Deep Zoom:

  • Exploration of very large or high-resolution images: A classic example of this would be zooming in on parts of a large map to see different levels of detail and then, using the mouse, moving your view around the map surface. As the user moves the view, animations are used to enhance the impression of moving from one place to the other on the image. Another example would be exploring a professional photo composition made up of high-resolution pictures.

  • 3-D photography: Take pictures of a room, one after the other creating a collection of photos that make up a 360-degree picture of the room. Now the user can pan around the room with each photo blending into the other.

  • Advertisements: You could create a relatively low resolution image to represent the overall theme of the ad, and then have progressively higher resolution images containing more impressions and data about the product. When the page the ad is embedded in first loads, the ad smoothly sharpens and draws the attention of the reader by loading subsequently higher resolution images. In addition, if the user's mouse enters the ad, different parts of the ad can zoom in.

To learn more about Deep Zoom, see Deep Zoom.

WriteableBitmap

The WriteableBitmap class represents an imaging class that you can manipulate at a lower level than specifying a PNG or JPEG source for the image. WriteableBitmap is used in the following scenarios:

  • As the return result of a webcam single image capture. For more information, see CaptureSource.

  • Converting image sources that are not accepted by the Silverlight client into acceptable formats of PNG or JPEG. This is an advanced scenario.

  • Creating an image source entirely from programmatic input, such as from a third party graphics library. This is an advanced scenario.

For more information, see WriteableBitmap.