2

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.

3

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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);
})

2 Comments

Hi, thank you very much for the solution. I do have control of the C# WinRT component. Is the conversion procedure same as this? And why would you recommend doing it in the component, is it a performance issue?
keeping things simple always helps. this code snippet does bytes -> IBuffer -> IInputStream -> MSStream -> URL whereas other one can do StorageFile->File->URL . btw, is there a reason to read bytes from file in c# winrt component. it can be done in the js code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.