3

Is there a way to convert a BitmapImage (Windows.UI.Xaml.Media.BitmapImage) to an Byte[] Array? Nothing I've tried work.... Another possible scenario (if BitmapImage cannot be converted to Byte array) is to download the image from web and then convert it to an array...

But I don't know how I can do that... It would be really nice, if someone have an idea.

Current try:

        HttpClient http = new HttpClient();
        Stream resp = await http.GetStreamAsync("http://localhost/img/test.jpg");

        var ras = new InMemoryRandomAccessStream();
        await resp.CopyToAsync(ras.AsStreamForWrite());

        BitmapImage bi = new BitmapImage();
        bi.SetSource(ras);


        byte[] pixeBuffer = null;

        using (MemoryStream ms = new MemoryStream())
        {
            int i = bi.PixelHeight;
            int i2 = bi.PixelWidth;
            WriteableBitmap wb = new WriteableBitmap(bi.PixelWidth, bi.PixelHeight);

            Stream s1 = wb.PixelBuffer.AsStream();
            s1.CopyTo(ms);

            pixeBuffer = ms.ToArray();
        }

But it doesn't work... i & i2 are always set to 0. So ras doesn't work correctly.... What's going on?

Thanks

Filip Skakun
  • 31,624
  • 6
  • 74
  • 100
user1011394
  • 1,656
  • 6
  • 28
  • 41

1 Answers1

1

In your code you're never waiting for the BitmapImage to load the image from the web, so it does not know its PixelWidth/PixelHeight when you access them. You could wait for it to load - for example using the AsyncUI library by calling "await bi.WaitForLoadedAsync()". This would not really help you here if you want to access the decoded pixels since BitmapImage does not give you access to the pixels and there is currently no API to convert a BitmapImage into a WriteableBitmap.

You can check an earlier question about the topic. You would need to get the image file from the web with something like HttpClient.GetAsync(), then load it using something like BitmapDecoder.

Community
  • 1
  • 1
Filip Skakun
  • 31,624
  • 6
  • 74
  • 100