将八位字节流转换为图像

时间:2016-05-29 14:01:57

标签: javascript image

我需要使用$ http.get获取文件。 数据以application / octet-stream的形式返回 但我知道这个文件是一张图片。

如何将此文件显示为图像?

我试过

var nuroImage = new Image();
nuroImage.onload = function {
  scope.imageSrc = this.src;
}

$http(req).then(
  funciton(response) {
    nuroImage.src = "data:application/octet-stream," + response.data
  }

我得到200ok,但图像没有显示

是否可以将八位字节流转换为jpeg / png?

3 个答案:

答案 0 :(得分:9)

您可以使用XMLHttpRequest()BlobURL.createObjectURL()的形式请求图片,以便从回复中创建blob网址

var nuroImage = new Image;
var request = new XMLHttpRequest();
request.responseType = "blob";
request.onload = function() {
  nuroImage.src = URL.createObjectURL(this.response)
}
request.open("GET", "/path/to/image/file");
request.send();

答案 1 :(得分:3)

我想你应该这样:

  • 使用RPC对生成的游程长度压缩图像文件进行编码
  • 并使用atob将其包含在html5文件中

如果您的文件不是PNG,请添加相应的mime类型。

<强>示例

<img src="data:image/png;base64,....">

答案 2 :(得分:-1)

如果这里有人使用 axios 并面临在图像/八位字节流或 base64 中转换应用程序/八位字节流二进制文件的问题,那么请不要使用 axios,您可以使用 fetch api of(modern browser to fetch api data)解决这个问题。

fetch('https://picsum.photos/536/354', {
    method: 'GET',
})
.then((data) => {
    // IMP to convert your json or other response to blob ( for this you have to check your api response is file / binary 
    return data.blob()
})
.then((data) => {
    var reader = new FileReader();
    reader.onload = function() {                         
        var b64 = reader.result
        console.log("This is base64", b64)
    }
    reader.readAsDataURL(data)
})
.catch((error) => {
    error.text().then( errorMessage => {
        console.log(errorMessage)
    })
})

相关问题