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

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

tutorialtime.info , on 8/10/2010 4:30:18 AM Said:

pingback

Pingback from tutorialtime.info

Tutorials Directory » Affordable RIA development USA | Affordable silverlight development USA

crazyvector.com , on 8/21/2010 6:42:53 AM Said:

pingback

Pingback from crazyvector.com

Affordable RIA development USA | Affordable silverlight development USA | Crazy Vector

technoforum.org , on 8/29/2010 9:12:27 AM Said:

pingback

Pingback from technoforum.org

Affordable RIA development USA | Affordable silverlight development USA | TechnoForum

gawix.pl , on 9/17/2010 1:37:58 PM Said:

pingback

Pingback from gawix.pl

Affordable RIA development USA |

So Rd's Blog , on 9/20/2010 12:31:39 PM Said:

trackback

Affordable RIA development_1116

<div style="word-break:break-all;width:650px;">
Affordable RIA development
A Silverlight development tutorial that shows you how to create your own 2D web based games. This series attempts to recreate a game originally developed with Fl

H6 Nt's Blog , on 9/21/2010 5:33:03 AM Said:

trackback

Affordable RIA development_5588

<div style="word-break:break-all;width:650px;">
Affordable RIA development
A Silverlight development tutorial that shows you how to create your own 2D web based games. This series attempts to recreate a game originally developed with Fl

X E's Blog , on 9/26/2010 5:04:26 PM Said:

trackback

Affordable RIA development_2652

<div style="word-break:break-all;width:650px;">
Affordable RIA development
A Silverlight development tutorial that shows you how to create your own 2D web based games. This series attempts to recreate a game originally developed with Fl

flashgames.bhou.net , on 10/2/2010 5:26:08 AM Said:

pingback

Pingback from flashgames.bhou.net

Affordable RIA development USA | Affordable silverlight development USA | Flash Games

Jr Bn's Blog , on 10/10/2010 2:34:33 AM Said:

trackback

Affordable RIA development_2575

</div>
A Silverlight development tutorial that shows you how to create your own 2D web based games. This series attempts to recreate a game originally developed with Flash,<a href="http://www.uggsoldes.net/" style="text-decoratio

Jb Bb's Blog , on 10/10/2010 10:32:35 AM Said:

trackback

Affordable RIA development_2575

</div>
A Silverlight development tutorial that shows you how to create your own 2D web based games. This series attempts to recreate a game originally developed with Flash, and can be used to highlight the differences between the two platforms.  W

Gb Rf's Blog , on 10/10/2010 10:34:41 AM Said:

trackback

Affordable RIA development_1116

</div>
A Silverlight development tutorial that shows you how to create your own 2D web based games. This series attempts to recreate a game originally developed with Flash, and can be used to highlight the differences between the two platforms.  W

H N's Blog , on 10/27/2010 1:40:28 AM Said:

trackback

Affordable RIA development_5588

</div>
A Silverlight development tutorial that shows you how to create your own 2D web based games. This series attempts to recreate a game originally developed with Flash,<a href="http://www.uggespana.org/" target="_blank"

Ho Mt's Blog , on 10/27/2010 7:49:14 AM Said:

trackback

Affordable RIA development_1116

</div>
A Silverlight development tutorial that shows you how to create your own 2D web based games. This series attempts to recreate a game originally developed with Flash, and can be used to highlight the differences between the two platforms.  W

O J's Blog , on 10/27/2010 9:05:54 PM Said:

trackback

Affordable RIA development_2652

</div>  A Silverlight development tutorial that shows you how to create your own 2D web based games. This series attempts to recreate a game originally developed with Flash, and can be used to highlight the differences between the two platforms.  W

adsense.kijciwoko.eu , on 11/9/2010 6:15:14 AM Said:

pingback

Pingback from adsense.kijciwoko.eu

Wszystko o google adsense  » Blog Archive   » Affordable RIA rozwoju USA

tutorialblogger.info , on 11/12/2010 6:39:20 PM Said:

pingback

Pingback from tutorialblogger.info

Affordable RIA development USA | Affordable silverlight development USA | Tutorial

Ga Cr's Blog , on 11/20/2010 12:02:03 PM Said:

trackback

Affordable RIA development_2652

</div>
A Silverlight development tutorial that shows you how to create your own 2D web based games. This series attempts to recreate a game originally developed with Flash,<a href="http://www.uggspaschere.com/" target="_blank&quo

superfinancialadvisor.net , on 12/3/2010 12:28:48 PM Said:

pingback

Pingback from superfinancialadvisor.net

Affordable RIA development USA | Affordable silverlight development USA | Financial Advisor - What is a Financial Advisor - Financial Help

animationshop.info , on 12/11/2010 7:53:44 AM Said:

pingback

Pingback from animationshop.info

Storyboard Animation Silverlight | ANIMATION

Pj Lo's Blog , on 12/12/2010 1:48:37 PM Said:

trackback

Affordable RIA development_1116

</div>
A Silverlight development tutorial that shows you how to create your own 2D web based games. This series attempts to recreate a game originally developed with Flash,<a href="http://www.canadagoosejacka.org/" title="canada

guiltyhippo.com , on 12/18/2010 7:18:32 AM Said:

pingback

Pingback from guiltyhippo.com

Taps Usa | Manufacturing & Metalworking

51obw573's Blog , on 12/31/2010 12:27:34 AM Said:

trackback

Affordable RIA development_1116

</div>
A Silverlight development tutorial that shows you how to create your own 2D web based games. This series attempts to recreate a game originally developed with Flash,<a href="http://www.cheapuggbootsinireland.com/" target="

flashmen.net , on 12/31/2010 9:34:42 PM Said:

pingback

Pingback from flashmen.net

Flash Usa | Buy Camera Flashes Here

siammaps.net , on 1/12/2011 7:00:38 PM Said:

pingback

Pingback from siammaps.net

USA Main – Affordable RIA development USA | Affordable silverlight development USA «  USA Maine Travel Blog

blogwalking.web.id , on 2/27/2011 1:10:05 AM Said:

pingback

Pingback from blogwalking.web.id

Localization and Globalization in WP7 Applications Using Resource Files | blogwalking.web.id - My blogwalking journey

firstchoicelocator.co.cc , on 3/14/2011 3:45:22 AM Said:

pingback

Pingback from firstchoicelocator.co.cc

Bitmap image | FirstChoiceLocator

games.777mom.com , on 5/20/2011 3:03:54 AM Said:

pingback

Pingback from games.777mom.com

Affordable RIA development USA- Silverlight development USA | games

gordenwebdesign.com , on 6/26/2011 3:01:27 PM Said:

pingback

Pingback from gordenwebdesign.com

Affordable RIA development USA- Silverlight development USA «  « Web Design Web Design

feulus.com , on 6/29/2011 6:06:07 AM Said:

pingback

Pingback from feulus.com

Affordable RIA development USA- Silverlight development USA | feulus.com

doctype.co , on 7/24/2011 5:38:41 AM Said:

pingback

Pingback from doctype.co

Affordable RIA development USA- Silverlight development USA | Doctype

kitco.tk , on 9/6/2011 12:05:40 AM Said:

pingback

Pingback from kitco.tk

How to Create 2D Web Based Games in C# | Kitco

savware.net , on 9/7/2011 8:21:25 PM Said:

pingback

Pingback from savware.net

Affordable RIA development USA | Affordable silverlight development USA »  SavWare

atm-lol.net , on 12/23/2011 7:08:17 PM Said:

pingback

Pingback from atm-lol.net

horoscopes

ezfreereport.com , on 12/24/2011 1:52:36 PM Said:

pingback

Pingback from ezfreereport.com

yasmin court case

Add comment


(Will show your Gravatar icon)

biuquote
  • Comment
  • Preview
Loading