WinJS, display image from a byte array?

穿精又带淫゛_ 提交于 2020-01-23 02:46:07

问题


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.


回答1:


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:


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


来源:https://stackoverflow.com/questions/15862421/winjs-display-image-from-a-byte-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!