2
votes

I'm looking for a way to display a JPEG image stored in a byte array. This is a Windows 8 Store App built in Javascript. The byte array is returned from a C# WinRT component. Its type in C# is byte[].

Basically, what I want is to get an object so that I can call:

URL.createObjectURL(bytearray, {oneTimeOnly: true});

upon. Currently this generates a runtime error because the array interface is not supported.

Thanks in advance.

2
Hmm.. I'm not looking for ways to download or transfer the file. How is xhr helpful in my case? The image is not from the web. - He Shiming
I am not pro in WinJS though, I found file to byte array solution, it might be helpful : stackoverflow.com/questions/14004190/… - Farhan Ghumra

2 Answers

3
votes

I discovered a far easier method.

var blob = new Blob([bytes], {type: "image/jpg"});
var url = URL.createObjectURL(blob, { oneTimeOnly: true });

Blob is actually supported directly by URL.createObjectURL. The only catch is that you have to specify a mime format to identify the buffer format, which in my case is possible.

2
votes

Current solution I found is quite round about. Hence, before giving the solution for bytes to URL, few comments:

  1. If there is better way to get to DOM stream/blob object from bytes, try out.
  2. If you control the winrt component - check if you can return StorageFile object. In that case - code will simplifyto

    var file = MSApp.createFileFromStorageFile(storageFile); var url = URL.createObjectURL(file, { oneTimeOnly: true });

now solution:

var bytes;
var memoryStream;    
var streams = Windows.Storage.Streams;
{

    // get IBuffer out of bytes
    var dataWriter = new streams.DataWriter();
    dataWriter.writeBytes(bytes);
    var buffer = dataWriter.detachBuffer();
    dataWriter.close();

    // get IInputStream out of IBuffer
    memoryStream = new streams.InMemoryRandomAccessStream();
    return memoryStream.writeAsync(buffer);
}).then(function onmemorystreamwritecomplete()
{
    var inputStream = memoryStream.getInputStreamAt(0);

    // get DOM MSStream from IInputStream
    var domMStream = MSApp.createStreamFromInputStream('image/jpg', inputStream);
    var url = URL.createObjectURL(domMStream, { oneTimeOnly: true });
    memoryStream.close();
    test3Img.setAttribute('src', url);
})