3

According to this, the following code can be used to convert a byte array into a BitmapImage:

public static async Task<BitmapImage> ByteArrayToBitmapImage(this byte[] byteArray)
{
    if (byteArray != null)
    {
        using (var stream = new InMemoryRandomAccessStream())
        {
            await stream.WriteAsync(byteArray.AsBuffer());
            var image = new BitmapImage();
            stream.Seek(0);
            image.SetSource(stream);
            return image;
        }
    }
    return null;
}

However, I get, "'System.Array' does not contain a definition for 'AsBuffer' and no extension method 'AsBuffer' accepting a first argument of type 'System.Array' could be found (are you missing a using directive or an assembly reference?)"

Is it that the "var stream" assignment is too vague (implicit typing) and I need to specify a particular data type for the "stream" var? Something other than System.Array?

Maybe this, from "Windows Store Apps Succinctly" is a clue: Buffers/byte arrays—System.Runtime.InteropServices.WindowsRuntime. WindowsRuntimeBufferExtensions: Extension methods in this class provide ways for moving between .NET byte arrays and the contents of WinRT buffers, exposed as IBuffer implementations.

...but if it is, that's not enough info for me to know what to do with it. Instead of "TMI" it's "NEI" (Not Enough Information).

B. Clay Shannon-B. Crow Raven
  • 8,547
  • 144
  • 472
  • 862

1 Answers1

8

The problem is that the compiler isn't finding the extension method AsBuffer(). Make sure you have a reference to the namespace System.Runtime.InteropServices.WindowsRuntime, i.e.

using System.Runtime.InteropServices.WindowsRuntime;

You also need to add a reference to the appropriate DLL, if you haven't already:

Namespace: System.Runtime.InteropServices.WindowsRuntime

Assembly: System.Runtime.WindowsRuntime (in System.Runtime.WindowsRuntime.dll)

Community
  • 1
  • 1
dbc
  • 104,963
  • 20
  • 228
  • 340
  • 2
    I tried to add the Reference, but got the err msg that it couldn't be added because it is already automatically referenced by the build system. So I added the using statement and it compiles. So that makes me wonder, if the needed reference is already there, why does VS not know that and give me a "Resolve" context menu item? Anyway, all's well that ends well, I guess - thanks! – B. Clay Shannon-B. Crow Raven Oct 24 '14 at 15:04