web 2.0

News: Windows Phone 7 Phones Running Silverlight


Load Bitmap Image From Resource in a Single Line of Code

If you read my recent article "How to Get Files From Resources in Silverlight 2.0", you'll see that loading a file embedded as resource takes only a few lines of code. You also have to remember the formats of the URI. Well, that is going to change today, because now you'll need to write just a single line of developer-friendly code.

I took the liberty to create a Resource Helper class with a couple methods such as GetStream(), GetBitmap() and GetString(). Let me demonstrate how to load an embedded bitmap:

img1.Source = ResourceHelper.GetBitmap("Images/EmbeddedInApplicationAssembly.png"); 

This will load image 'EmbeddedInApplicationAssembly.png' into the image element 'img1'. It doesn't matter whether if you set the 'Build Action' property of the file to 'Resource' or 'Content', because these methods will automatically detect if the file is embedded in assembly or in .xap package. You can change the 'Build Action' property of the files, yet the code will work without any change.

What if the file is embedded in a library assembly instead of application assembly? Ok, here's a working example on how to load the file:

img3.Source = ResourceHelper.GetBitmap(
    "ImageFiles/EmbeddedInLibraryAssembly.png", "SilverlightClassLibrary1");

This code loads the 'EmbeddedInLibraryAssembly.png' image that is embedded in 'SilverlightClassLibrary1.dll' library.

Download and Demo

For more examples, please refer to these sample projects.

SilverlightResourceReading.zip (113.88 kb)  VB.NET and C# Project files

Online Demo 


Tags: ,

Silverlight 2.0 | Tutorial