web 2.0

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

Comments

s_svane , on 4/24/2008 7:38:34 PM Said:

s_svane

Hi, super job. so much easier that doing the old way.

Bruce Martin , on 5/6/2008 3:55:22 AM Said:

Bruce Martin

I tried your helper class today, but got the following error, which returned "Nothing" from the GetStream function (using the VB version).
The immediate window result shows the problem (I think?).

?New Uri(assemblyName & ";component/" & relativeUri, UriKind.Relative)
{System.Uri}
    AbsolutePath: {System.InvalidOperationException}
    AbsoluteUri: {System.InvalidOperationException}
    DnsSafeHost: {System.InvalidOperationException}
    Fragment: {System.InvalidOperationException}
    Host: {System.InvalidOperationException}
    IsAbsoluteUri: False
    IsUnc: {System.InvalidOperationException}
    LocalPath: {System.InvalidOperationException}
    OriginalString: "Forecaster;component/../../Images/Toolbar/deletecost.png"
    Port: {System.InvalidOperationException}
    Query: {System.InvalidOperationException}
    Scheme: {System.InvalidOperationException}
    SchemeDelimiter: "://"
    UriSchemeFile: "file"
    UriSchemeFtp: "ftp"
    UriSchemeGopher: "gopher"
    UriSchemeHttp: "http"
    UriSchemeHttps: "https"
    UriSchemeMailto: "mailto"
    UriSchemeNetPipe: "net.pipe"
    UriSchemeNetTcp: "net.tcp"
    UriSchemeNews: "news"
    UriSchemeNntp: "nntp"
    UserEscaped: False
    UserInfo: {System.InvalidOperationException}

?New Uri(relativeUri, UriKind.Relative)
{System.Uri}
    AbsolutePath: {System.InvalidOperationException}
    AbsoluteUri: {System.InvalidOperationException}
    DnsSafeHost: {System.InvalidOperationException}
    Fragment: {System.InvalidOperationException}
    Host: {System.InvalidOperationException}
    IsAbsoluteUri: False
    IsUnc: {System.InvalidOperationException}
    LocalPath: {System.InvalidOperationException}
    OriginalString: "../../Images/Toolbar/deletecost.png"
    Port: {System.InvalidOperationException}
    Query: {System.InvalidOperationException}
    Scheme: {System.InvalidOperationException}
    SchemeDelimiter: "://"
    UriSchemeFile: "file"
    UriSchemeFtp: "ftp"
    UriSchemeGopher: "gopher"
    UriSchemeHttp: "http"
    UriSchemeHttps: "https"
    UriSchemeMailto: "mailto"
    UriSchemeNetPipe: "net.pipe"
    UriSchemeNetTcp: "net.tcp"
    UriSchemeNews: "news"
    UriSchemeNntp: "nntp"
    UserEscaped: False
    UserInfo: {System.InvalidOperationException}

Bruce Martin , on 5/6/2008 7:18:44 AM Said:

Bruce Martin

I see now that the image file path used as a parameter to the ResourceHelper.GetBitmap() function should be relative to the project, and not relative to the calling routine's position. Since I have my user controls in a sub directory, my xaml file had this statement (which works):
<Image x:Name="ButtonImage" Height="36" Width="36" Source="../../Images/Toolbar/newforecast.png" />.

So when I wanted to use your code to change the image from the user control's code behind, I used the "../../Images/Toolbar/newforecast.png" path. This didn't work. So to verify my idea that the path should be relative to the project, I went back to your sample.

I went to your sample and added a subfolder under Images, and put an image file there. I changed your code from:
img1.Source = ResourceHelper.GetBitmap("Images/EmbeddedInApplicationAssembly.png")
to:
img1.Source = ResourceHelper.GetBitmap("Images/ImagesSubFolder/EmbeddedInApplicationAssembly.png")
but now that doesn't work either.

Am I doing something wrong?


?assemblyName & ";component/" & relativeUri
"ResourceReadingSample;component/Images/ImagesSubFolder/EmbeddedInApplicationAssembly.png"

Bruce Martin , on 5/6/2008 7:37:28 AM Said:

Bruce Martin

Well trying the same code in my project works correctly. Thanks for the great solution. Sorry about jamming up your blog with my junk.

Neo , on 5/7/2008 1:44:46 AM Said:

Neo

Hi Bruce, I'm glad you could configure it out the problem. So which code works correctly?

blogs.codes-sources.com , on 8/21/2008 1:14:48 AM Said:

pingback

Pingback from blogs.codes-sources.com

[Silverlight] - Créer un contrôle réutilisable et des propriétés personnalisées. , Danuz

ohaiyo , on 10/13/2008 2:27:40 PM Said:

ohaiyo

i wanna to be know, how to get all *.png file in assembly or content?

devlicious.com , on 10/17/2008 4:39:31 AM Said:

pingback

Pingback from devlicious.com

Frame-based Bitmap Animations in Silverlight - Christopher Bennage

feeds.feedburner.com , on 10/17/2008 5:12:44 AM Said:

pingback

Pingback from feeds.feedburner.com

Frame-based Bitmap Animations in Silverlight - Christopher Bennage

bold , on 10/22/2008 5:06:17 PM Said:

bold

Hello, I am not able to use it in my project. ( however, your projects compiles correctly and runs fine.) Can you you please tell me what kind Silverlight project you build? and what Silverlight ver. you are using. thanks.

Error  1  The type or namespace name 'FontSource' could not be found (are you missing a using directive or an assembly reference?)  C:\...\Controls\MyButton.cs  83

Error  2  The best overloaded method match for 'System.Windows.Markup.XamlReader.Load(System.Xml.XmlReader)' has some invalid arguments  C:\...\Controls\MyButton.cs  103

I have all the using statements as you have in your ResourceHelper.cs file. Any help please?

Keith , on 10/30/2008 9:09:53 AM Said:

Keith

I installed ResourceHelper.cs in a class Screen which includes a dir Resources.  Resources contains a .png file.  I execute the call with no problem.  All works well.

   spriteBrush.ImageSource =  ResourceHelper.GetBitmap
             ("Resources/ScWand1024.png");

Then I added to the Resource dir a .txt file.  I run

   string txt1 = ResourceHelper.GetString("Resources/Text.txt");

and it fails on the line in the sub GetStream (both being called in the same sub).
   StreamResourceInfo res = Application.GetResourceStream(new Uri
(assemblyName + ";component/" + relativeUri, UriKind.Relative));

Adding to the confusion.  I had downloaded an example from another source that (Chris from the pingback) was demoing the functions. He pointed us to here for the download.  This function call works just fine in the sample project.  

Both calls get to the same palce and the only difference is the relativeURi.  The GetString returns a Null, but no error.  I could understand where I goofed in many places, but with the GetBitmap working, I cannot understand why GetString fails.

I found one place that suggested removing all the *.resource files.  DId that.. no diff.

I Also checked the properties.  They seem ok.  They match the ones in the prjoject that is working.

Things like this usually turn out to be Stupid Coder Error, especially when its working somewhere else.  But I thought I would ask if there are any suggestions.






Jasper , on 11/4/2008 11:30:12 PM Said:

Jasper

Hi,

I am using this approach with success, so thanks for pointing out this direction!

I do have an "issue". Is there a way to get this working at designtime?
<Image Source="/ResourceLibrary;component/images/image.png"/>

Right now in designtime i can't seem to get the image visible?

Thanks!

Jasper

Croatia hotels , on 11/7/2008 2:39:13 AM Said:

Croatia hotels

Thanks for sharing. thanks

Anonymous , on 4/23/2009 4:26:55 PM Said:

Anonymous

Very nice. Works like a charm.

Thanks a lot for the explanation on handling resources with SL.

7dollartemplates.com , on 7/30/2009 11:53:21 AM Said:

pingback

Pingback from 7dollartemplates.com

Affordable RIA development USA | Affordable silverlight development USA | 7 Dollart Templates

amillionlittlepixels.com , on 7/30/2009 12:32:49 PM Said:

pingback

Pingback from amillionlittlepixels.com

Affordable RIA development USA | Affordable silverlight development USA » A Million Little Pixels | A Million Little Pixels

Online video slot machine game , on 7/30/2009 9:57:55 PM Said:

Online video slot machine game

Thanks! I'm writing a quick program now that will allow me to choose a bitmap file and have all the header information displayed in a window cause it will help me out here and probably in future as well.

Pete , on 8/20/2009 8:12:14 PM Said:

Pete

Nice, simple and effective method. Thanks for posing it.

CreditReportStore.info , on 9/1/2009 10:22:23 AM Said:

pingback

Pingback from CreditReportStore.info

How to Create 2D Web Based Games in C# | The Credit Report Store

giocate ai casinò online , on 9/26/2009 1:41:56 AM Said:

giocate ai casinò online


This article gives the light in which we can observe the reality. this is very nice one and gives in depth information. thanks for this nice article Good post.....Valuable information for all.I will recommend my friends to read this for sure…

http://rapid4me.com , on 10/5/2009 1:06:29 AM Said:

http://rapid4me.com

Are you going to continue this issue? I'd like to read more on this topic. All this is still a mistery to me...

Hrvatska , on 10/10/2009 8:30:33 PM Said:

Hrvatska

Doesn working for me Frown

I guess Il have to put some more effort into it Smile

<a href="http://www.direct-croatia.com">Hrvatska danas</a>

little house on the prairie dvd , on 10/20/2009 8:03:55 AM Said:

little house on the prairie dvd

How convenient, I've go to find a place to use this

visapoint.eu.com , on 3/12/2010 9:54:38 AM Said:

pingback

Pingback from visapoint.eu.com

Technical News  » Blog Archive   » Affordable RIA development USA | Affordable silverlight development USA

staringfrog.com , on 3/28/2010 1:42:56 AM Said:

pingback

Pingback from staringfrog.com

Game Development and Game Programming | Affordable RIA development USA | Affordable silverlight development USA

23.mfbattle.com , on 5/20/2010 6:35:36 AM Said:

pingback

Pingback from 23.mfbattle.com

Rx350 Autos Lincoln Mkx, Discount Lexus Rx350 Specs

bhbodeezy.com , on 5/31/2010 9:25:10 PM Said:

pingback

Pingback from bhbodeezy.com

Affordable RIA development USA | Affordable silverlight development USA | BHBodeezy

silverlightthai.muict.net , on 6/7/2010 6:16:11 AM Said:

pingback

Pingback from silverlightthai.muict.net

Affordable RIA development USA | Affordable silverlight development USA «  Silverlight Thailand

ruige.tk , on 7/24/2010 2:20:15 AM Said:

pingback

Pingback from ruige.tk

Affordable RIA development USA | Affordable silverlight development USA «  Ruige Zhu blog

silvercornucopia.com , on 7/29/2010 11:45:46 AM Said:

pingback

Pingback from silvercornucopia.com

Tutorial Silverlight | Silver Cornucopia ...

allourweb.com , on 7/29/2010 4:26:10 PM Said:

pingback

Pingback from allourweb.com

Affordable RIA development USA | Affordable silverlight development USA

Add comment


(Will show your Gravatar icon)

biuquote
  • Comment
  • Preview
Loading