Downloading image from internet into local folder and using it as a texture2d.

I have been unable to download an image from the internet into the local folder and succeed in using it as a texture2d.

I have been able to download the image just fine. I have not found the combination of streams or magic to make the image stored inside a texture2d variable.

Content.Load is expecting me to come from the standard content folder, except I’m stuck in the ApplicationData local folder.

Could anyone help?

Texture2D.FromStream ?
http://msdn.microsoft.com/en-us/library/ff434103.aspx

Support will depend on what platform you are on, but it should work on most

With what stream?

        Stream stream3 = TitleContainer.OpenStream("Content/01d.png");

        Texture2D testing = Texture2D.FromStream(GraphicsDevice, stream3);

The TitleContainer is still behaving with relative pathing. Any streams that can access the ApplicationData?

You can use any type of stream. It doesn’t have to come from TitleContainer or the ContentManager. What did you use to write the file to disk?

            HttpClient httpClient = new HttpClient();
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, source);
            response = await httpClient.SendAsync(request,
                HttpCompletionOption.ResponseHeadersRead);
            
            imgfile = await ApplicationData.Current.LocalFolder.CreateFileAsync("test.png", CreationCollisionOption.FailIfExists);
            var fs = await imgfile.OpenAsync(FileAccessMode.ReadWrite);
            DataWriter writer = new DataWriter(fs.GetOutputStreamAt(0));
            writer.WriteBytes(await response.Content.ReadAsByteArrayAsync());
            await writer.StoreAsync();
            writer.DetachStream();
            await fs.FlushAsync();

Some way to reverse this to be a reader?

There are extension methods to convert between WinRT streams and .NET streams.

1 Like
        StorageFile imgfile = await ApplicationData.Current.LocalFolder.CreateFileAsync("bubbles.png", CreationCollisionOption.OpenIfExists);

        var fs = await imgfile.OpenAsync(FileAccessMode.Read);

        test = Texture2D.FromStream(GraphicsDevice, fs.AsStream());

This code, so beautiful and elegant. Thank you good sir for pointing out the AsStream function to me.