Javascript 将八位字节流转换为图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37510801/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 20:24:12  来源:igfitidea点击:

Convert octet-stream to image

javascriptimage

提问by doron

I need to fetch a file using a $http.get. The data returns as application/octet-stream But i know this file is an image.

我需要使用 $http.get 获取文件。数据作为应用程序/八位字节流返回但我知道这个文件是一个图像。

How can i display this file as an image?

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

I tried

我试过

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

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

I get 200ok but the image isn't showing

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

Is it possible to transform octet-stream to jpeg/png?

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

采纳答案by guest271314

You can use XMLHttpRequest()to request image as Blob, URL.createObjectURL()to create a blob URL from response

您可以使用XMLHttpRequest()将图像请求为BlobURL.createObjectURL()从响应创建一个 blob URL

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

回答by gevorg

I guess you should something like this:

我想你应该是这样的:

  • Use atobto encode the resulting run-length compressed image file
  • And use <img src="data:image/png;base64,....">to include that into the html5 file
  • 使用atob编码生成的行程长度压缩的图像文件
  • 并用于<img src="data:image/png;base64,....">将其包含到 html5 文件中

If your file is not PNG, do add corresponding mime type.

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

Sample:

样品

<img src="data:image/gif;base64,R0lGODlhEAAOALMAAOazToeHh0tLS/7LZv/0jvb29t/
f3//Ub//ge8WSLf/rhf/3kdbW1mxsbP//mf///yH5BAAAAAAALAAAAAAQAA4AAARe8L1Ekyky67
QZ1hLnjM5UUde0ECwLJoExKcppV0aCcGCmTIHEIUEqjgaORCMxIC6e0CcguWw6aFjsVMkkIr7g7
7ZKPJjPZqIyd7sJAgVGoEGv2xsBxqNgYPj/gAwXEQA7"/>