Posts Tagged with BitmapImage

Loading images in Silverlight 2

Reading through the Silverlight.net forum I still see a ton of people struggling with how to load an image procedurally. I thought it would be beneficial to included a quick sample of four different ways you can set the Image.Source property within Silverlight 2.

image_loading1




Image 1 - Resource Loaded via XAML - The easiest and most common way to load an image is to include the image in your project and set its "Build Action" to Resource. This will embedded the image within the primary assembly which gets packaged in your projects XAP file. Here is what that assembly looks like if you explore it with Reflector.

image_loading3


To reference this embedded resource within xaml, you can set the source attribute equal to the following

<Image Source="ImageSource;component/1.jpg"…>

Image 2 - Resource Loaded procedurally - In the event that you need to swap or load an images source procedurally, you can simply load up a BitmapImage via a relative URI and set the Image.Source equal to this object.

//Image 2 - Loaded via bitmap image data
// - Build Action=Resource
// - Copy to Output Directory = Do Not Copy
BitmapImage bmpImg2 = new BitmapImage()
Uri uri2 = new Uri(&quot2.jpg&quot, UriKind.Relative)
bmpImg2.UriSource = uri2
image2.Source = bmpImg2

Image 3 - Build Action = Content – If you do not desire to embed an image within your assembly, you can set its build action to “Content” and that image will be packaged within the XAP.

XAP File


//Image 3 - Load image that is included in the XAP file
// - Build action = Content
// - Copy to Output Directory = Do Not Copy
BitmapImage bmpImg3 = new BitmapImage()
Uri uri3 = new Uri(&quot/3.jpg&quot, UriKind.Relative)
bmpImg3.UriSource = uri3
image3.Source = bmpImg3

(Note: The image file name in the URI is proceeded with a front slash (/).  This is required to indicate that the image is relative to the location of the assembly.)


Image 4 - Build Action = None / Copy to Output Directory = Copy always - In the instance that you don’t want the image to be downloaded locally (packaged in XAP), you can set the “Build Action” equal to “None” and set the “Copy to Output Directory” equal to “Copy always”.  /bin directory


Using the “TestPage.html” page which is automatically generated in your projects “bin” directory you can reference the image location relatively, just as you did in sample 3.

//Image 4 - Load image that is located at some relative url
// - Build action = None
// - Copy to Output Directory = Copy always 
//      (Note: I had to manually copy the image to 
//       my web projects ClientBin directory)
BitmapImage bmpImg4 = new BitmapImage()
Uri uri4 = new Uri(&quot/4.jpg&quot, UriKind.Relative)
bmpImg4.UriSource = uri4
image4.Source = bmpImg4

Code: ImageSource.zip