This blog is no longer updated please visit http://www.createdbyx.com/ instead.

Monday, May 17, 2004

Revisited: How to create a D3DTexture from an embeded image resource.

I have continued to play around with loading embeded resource data files and have come up with a alternative way to create a D3DTexture from an embeded resource image. This new method seems more apropreate. (To me at least :p )

If you are wondering why I am loading embeded resource images rather than simply loading and creating a D3D texture from a file, it is because external files can be lost and can result in you app not being able to run. Not that I will be doing this for every app I write!



Protected Friend Function LoadResource(ByVal ResourceName As String) As IO.MemoryStream
Dim ResourceStream As IO.Stream
ResourceStream = Reflection.Assembly.GetExecutingAssembly.GetManifestResourceStream(ResourceName)
If ResourceStream Is Nothing Then Return Nothing

Dim byts(CInt(ResourceStream.Length - 1)) As Byte
Dim Len As Integer = ResourceStream.Read(byts, 0, CInt(ResourceStream.Length))

Dim MemStream As New IO.MemoryStream(byts, 0, Len)
Return MemStream
End Function


Protected Friend Function LoadResourceImage(ByVal ResourceImageName As String) As Direct3D.Texture
Dim Mem As IO.MemoryStream
Mem = LoadResource(ResourceImageName)

' attempt to load/create image we saved to memory stream
Dim Tex As Direct3D.Texture
Tex = Direct3D.TextureLoader.FromStream(mobjGraphics.Device, Mem)

' done with varibles
Mem.Close()
Mem = Nothing

' return reference to texture
Return Tex
End Function

Sunday, May 16, 2004

How to create a D3DTexture from an embeded image resource.

I have added a cool little code snip that demonstrates a way of loading a image that was added to a project and declared "Embeded Resource" at design time, and returns a newly created D3D texture.
The code is written in vb.net and DX9.

Load Resource Texture
Private Function LoadResourceImage(ByVal ResourceImageName As String) As Direct3D.Texture

Dim Mem As New IO.MemoryStream()
Dim Img As Bitmap

' attempt to create bitmap from embeded resource
Img = New Bitmap(Me.GetType, ResourceImageName)
' save image to memory stream
Img.Save(Mem, Drawing.Imaging.ImageFormat.Png)
' seek to start of stream
Mem.Seek(0, IO.SeekOrigin.Begin)

' attempt to load/create image we saved to memory stream
Dim Tex As Direct3D.Texture
Tex = Direct3D.TextureLoader.FromStream(mobjGraphics.Device, Mem)

' done with varibles
Mem.Close()
Mem = Nothing
Img.Dispose()
Img = Nothing

' return reference to texture
Return Tex
End Function