ArrayBuffer转jpeg

时间:2019-02-03 04:25:45

标签: javascript arraybuffer typed-arrays

我正在从python服务器流式传输ArrayBuffers,并尝试使用javascript将每个端口解释为映像。它们在javascript中作为arraybuffers接收。但是我无法通过图像标签src属性使它们可读。我试过将它们生成为Blob对象,然后使用window.URL.createObjectURL(blob)。那也没有用。

blob网址看起来像这样的blob:null / e2836074-64b5-4959-8211-da2fc24c35a6错了吗?

有没有建议/知道解决方案。

非常感谢。

var arrayBuffer = new Uint8Array(stream.data);
var blob = new Blob([arrayBuffer], {type: "image/jpeg"});
var urlCreator = window.URL || window.webkitURL;
var imageUrl = urlCreator.createObjectURL( blob );
console.log(imageUrl);
img.src = imageUrl;

array buffer image

1 个答案:

答案 0 :(得分:0)

如果您对事物有任何控制权,则应在Javascript调用中使用blob的responseType。这样一来,您可以直接使用从服务器获取的数据,而不必尝试通过ArrayBuffer进行访问

有关示例,请参见以下小提琴:https://jsfiddle.net/ort74gmp/

// Simulate a call to Dropbox or other service that can
// return an image as a blob
var xhr = new XMLHttpRequest();

// Use JSFiddle logo as a sample image to avoid complicating
// this example with cross-domain issues.
xhr.open( "GET", "https://fiddle.jshell.net/img/logo.png", true );

// Ask for the result as an ArrayBuffer.
xhr.responseType = "blob";

xhr.onload = function( e ) {
    var blob = this.response;
    var reader = new FileReader();
    reader.onload = function() {
        var dataURL = reader.result;
      document.querySelector('#photo').src = dataURL;
    }
    reader.readAsDataURL(blob);
};

xhr.send();