I am trying to load some images via HTTP streams into a Texture2D.
The code I have written uses a HttpWebRequest to get a Stream from a URL. It then reads that Stream into a MemoryStream, and passes the MemoryStream into Texture2D.FromFile which keeps chucking out an InvalidOperationException:
System.InvalidOperationException was unhandled
Message="An unexpected error has occurred."
Source="Microsoft.Xna.Framework"
StackTrace:
at Microsoft.Xna.Framework.Graphics.Texture.GetTextureInformation(String filename)
at Microsoft.Xna.Framework.Graphics.Texture.FromFile(GraphicsDevice graphicsDevice, String filename)
at Microsoft.Xna.Framework.Graphics.Texture.FromFile(GraphicsDevice graphicsDevice, Stream textureStream, Int32 numberBytes)
at Microsoft.Xna.Framework.Graphics.Texture2D.FromFile(GraphicsDevice graphicsDevice, Stream textureStream)
at XNAVirtualEarth.WebImage..ctor(Game game, String uri) in C:\Documents and Settings\Leith Bade\My Documents\Visual Studio 2008\Projects\XNAVirtualEarth\XNAVirtualEarth\WebImage.cs:line 38
at XNAVirtualEarth.Game1.LoadContent() in C:\Documents and Settings\Leith Bade\My Documents\Visual Studio 2008\Projects\XNAVirtualEarth\XNAVirtualEarth\Game1.cs:line 51
at Microsoft.Xna.Framework.Game.Initialize()
at XNAVirtualEarth.Game1.Initialize() in C:\Documents and Settings\Leith Bade\My Documents\Visual Studio 2008\Projects\XNAVirtualEarth\XNAVirtualEarth\Game1.cs:line 39
at Microsoft.Xna.Framework.Game.Run()
at XNAVirtualEarth.Program.Main(String[ args) in C:\Documents and Settings\Leith Bade\My Documents\Visual Studio 2008\Projects\XNAVirtualEarth\XNAVirtualEarth\Program.cs:line 14
InnerException:
Here is the code that creates the Texture2D:
| HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri); |
| HttpWebResponse response = (HttpWebResponse)request.GetResponse(); |
| Stream webStream = response.GetResponseStream(); |
| |
| Stream cachedStream = CacheStream(webStream); |
| |
| webStream.Close(); |
| response.Close(); |
| |
| texture = Texture2D.FromFile(Game.GraphicsDevice, cachedStream); |
| |
| cachedStream.Close(); |
Here is CacheStream:
| Stream CacheStream(Stream stream) |
| { |
| Stream cachedStream = new MemoryStream(); |
| |
| const int bufferSize = 1500; |
| byte[ buffer = new byte[bufferSize]; |
| |
| int read = 0; |
| |
| while ((read = stream.Read(buffer, 0, bufferSize)) != 0) |
| { |
| cachedStream.Write(buffer, 0, read); |
| } |
| |
| return cachedStream; |
| } |
I have tried with PNGs (with and without transparency) and JPEG, none of which work.
Someone here must know whats going on.