.comment-link {margin-left:.6em;}


Friday, February 18, 2005

Embedding images

One day you might encounter a user who has done some cleaning (thouroughly) on his PC. Your program crashes because it can't find some necessary files...
A reinstall will do the trick, but there's a more user-friendly way to cope with 'deleters'.
I'm going to use images in my example, but you could do this with every file you want (since you'll be getting a Stream).

Add an image to your project and make sure to put the Build Action to Embedded Resource.

Now here's some code to retrieve the image, the function GetEmbeddedImagePath() will return the filename, the function GetEmbeddedImage() will return an Image object. They both need 1 parameter, the name of the image you want to retrieve.

Public Shared Function GetEmbeddedImagePath(ByVal imageName As String) As String
Dim f, fn As String
f = Application.StartupPath
If Not f.EndsWith("\") Then f &= "\"
f &= "Images\"
fn = f & imageName
If File.Exists(fn) Then
Return fn
If Not Directory.Exists(f) Then
End If
Dim s As Stream = GetExecutingAssembly.GetManifestResourceStream(GetExecutingAssembly.GetName.Name & "." & imageName)
If not s Is Nothing Then
Dim i As Image = Bitmap.FromStream(s)
Return fn
End If
End If
Return Nothing
End Function

Public Shared Function GetEmbeddedImage(ByVal imageName As String) As Image
Dim fn As String = GetEmbeddedImagePath(imageName)
If Not fn Is Nothing Then
Return Image.FromFile(fn)
End If
Return Nothing
End Function


Post a Comment

Links to this post:

Create a Link

<< Home

Stefanie Worm is het liefste vrouwtje van de wereld.
Melina is de liefste schatsie van de wereld (Erik De Maeyer).