Silverlight Tip of the Day #86 – How to Load External Images
In Tip of the Day #84 I discussed the importance of being able to load controls from server side components (DLL’s) on demand rather than packaging everything together for one large client side download. The same principle applies to images. Let’s say your game has a large library of images that it needs for the game. Not all of these images will be needed at the start of the game. In this tip I will show you how to dynamically load these image resources from the server as needed.
To download an image from a server start by creating a BitmapImage. You will need to add a using statement to reference System.Windows.Media.Imaging. After you have created a BitmapImage point its UriSource to the absolute path of the image file you want to download from the Internet. To illustrate this I have used http://www.silverligthdev.net/images/myImage.png. Next, set the Source of your Image control to point to the BitmapImage.
Example XAML that contains the Image you will load:
<Canvas x:Name="LayoutRoot" Background="White">
<Image x:Name="MyImage"></Image>
</Canvas>
The following C# code shows you how to load the image source from a file on a server. When the image is 100% loaded the event ImageOpened is fired.
public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
BitmapImage bi = new BitmapImage();
bi.UriSource = new Uri("http://www.silverlightdev.net/images/blogImages/Sample.png");
MyImage.Source = bi;
MyImage.ImageOpened += new EventHandler<RoutedEventArgs>(MyImage_ImageOpened);
}
void MyImage_ImageOpened(object sender, RoutedEventArgs e)
{
// Image load complete.
}
}
Thank you,
--Mike Snow
Subscribe in a reader