2

So my app gets a BitmapImage from a url, which works, and I then need to assign that image to a writeablebitmap. For the moment I have this:

        Debug.WriteLine("Poster opened for loading. Url=" + e);
        BitmapImage img = new BitmapImage(new Uri(e));
        Backdrop.Source = img;
        img.ImageOpened += async (s, e1) =>
        {
            WriteableBitmap wbm = new WriteableBitmap(((BitmapImage)s).PixelWidth, ((BitmapImage)s).PixelHeight);
            var storageFile = await StorageFile.GetFileFromApplicationUriAsync(new Uri(e));
            using (var stream = await storageFile.OpenReadAsync())
            {
                await wbm.SetSourceAsync(stream);
            }
        };

Which is really awful code, but it all works until StorageFile.GetFileFromApplicationUriAsync(), where I'm told the Value falls within an unexpected range. I'm guessing this is because it only acceps the "ms-appx:///" format, and not "http://". Is there any way to get this working? And eventually in a cleaner way? I thought this would be easy, but it's a nightmare. I've been trying to do this since yesterday.

P.S. I know this might appear like a duplicate, but I have found absolutely nothing on StackOverflow that actually works.

user2950509
  • 1,018
  • 2
  • 14
  • 37

1 Answers1

2

Try this:

var httpClient = new HttpClient();
var buffer = await httpClient.GetBufferAsync(pictureUri);
var writeableBitmap = new WriteableBitmap(width, height);

using (var stream = buffer.AsStream())
{
    await writeableBitmap.SetSourceAsync(stream.AsRandomAccessStream());
}
Andrei Ashikhmin
  • 2,401
  • 2
  • 20
  • 34
  • This idea worked, but I had to change it to get the stream like this for it to work with uwp (httpClient doesn't have .GetBufferAsync): var buffer = await httpClient.GetByteArrayAsync(e); MemoryStream str = new MemoryStream(buffer); – user2950509 Mar 11 '16 at 21:54
  • 1
    There are two different HttpClients in UWP, one in Windows.Web.Http namespace and another one in System.Net.Http. As far as I remember, Microsoft recommends to use the one in Windows.Web.Http, and it does have GetBufferAsync method. But you can use either one for my example. – Andrei Ashikhmin Mar 11 '16 at 22:01