使用 JavaScript 显示 Blob

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7650587/
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-24 03:03:50  来源:igfitidea点击:

Using JavaScript to display a Blob

javascriptimagebase64blob

提问by GAgnew

I am retrieving a Blob image from a database, and I'd like to be able to view that image using JavaScript. The following code produces a broken image icon on the page:

我正在从数据库中检索 Blob 图像,并且希望能够使用 JavaScript 查看该图像。以下代码在页面上生成一个损坏的图像图标:

var image = document.createElement('image');
    image.src = 'data:image/bmp;base64,'+Base64.encode(blob);
    document.body.appendChild(image);

Here is a jsFiddlecontaining all the code required, including the blob. The completed code should properly display an image.

这是一个包含所有所需代码的 jsFiddle,包括 blob。完成的代码应正确显示图像。

采纳答案by GAgnew

The problem was that I had hexadecimal data that needed to be converted to binary before being base64encoded.

问题是我有十六进制数据需要在 base64encoded 之前转换为二进制。

in PHP:

在 PHP 中:

base64_encode(pack("H*", $subvalue))

回答by AdamZ

You can also get BLOB object directly from XMLHttpRequest. Setting responseType to blob makes the trick. Here is my code:

您还可以直接从 XMLHttpRequest 获取 BLOB 对象。将 responseType 设置为 blob 可以解决问题。这是我的代码:

var xhr = new XMLHttpRequest();
xhr.open("GET", "http://localhost/image.jpg");
xhr.responseType = "blob";
xhr.onload = response;
xhr.send();

And the response function looks like this:

响应函数如下所示:

function response(e) {
   var urlCreator = window.URL || window.webkitURL;
   var imageUrl = urlCreator.createObjectURL(this.response);
   document.querySelector("#image").src = imageUrl;
}

We just have to make an empty image element in HTML:

我们只需要在 HTML 中创建一个空的图像元素:

<img id="image"/>

回答by Ogglas

If you want to use fetch instead:

如果您想改用 fetch:

var myImage = document.querySelector('img');

fetch('flowers.jpg').then(function(response) {
  return response.blob();
}).then(function(myBlob) {
  var objectURL = URL.createObjectURL(myBlob);
  myImage.src = objectURL;
});

Source:

来源:

https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

回答by nkron

You can convert your string into a Uint8Arrayto get the raw data. Then create a Blobfor that data and pass to URL.createObjectURL(blob)to convert the Blob into a URL that you pass to img.src.

您可以将字符串转换为Uint8Array以获取原始数据。然后为该数据创建一个Blob并传递给URL.createObjectURL(blob)以将 Blob 转换为您传递给img.src的 URL 。

var data = '424D5E070000000000003E00000028000000EF...';

// Convert the string to bytes
var bytes = new Uint8Array(data.length / 2);

for (var i = 0; i < data.length; i += 2) {
    bytes[i / 2] = parseInt(data.substring(i, i + 2), /* base = */ 16);
}

// Make a Blob from the bytes
var blob = new Blob([bytes], {type: 'image/bmp'});

// Use createObjectURL to make a URL for the blob
var image = new Image();
image.src = URL.createObjectURL(blob);
document.body.appendChild(image);

You can try the complete example at: http://jsfiddle.net/nj82y73d/

您可以在以下位置尝试完整示例:http: //jsfiddle.net/nj82y73d/

回答by nachito

In your example, you should createElement('img').

在您的示例中,您应该createElement('img').

In your link, base64blob != Base64.encode(blob).

在您的链接中,base64blob != Base64.encode(blob).

This works, as long as your data is valid http://jsfiddle.net/SXFwP/(I didn't have any BMP images so I had to use PNG).

只要您的数据有效http://jsfiddle.net/SXFwP/(我没有任何 BMP 图像,所以我不得不使用 PNG),这就有效。

回答by marius_neo

I guess you had an error in the inline code of your image. Try this :

我猜您在图像的内联代码中有错误。尝试这个 :

var image = document.createElement('img');
    
image.src="data:image/gif;base64,R0lGODlhDwAPAKECAAAAzMzM/////wAAACwAAAAADwAPAAACIISPeQHsrZ5ModrLlN48CXF8m2iQ3YmmKqVlRtW4MLwWACH+H09wdGltaXplZCBieSBVbGVhZCBTbWFydFNhdmVyIQAAOw==";
    
image.width=100;
image.height=100;
image.alt="here should be some image";
    
document.body.appendChild(image);

Helpful link :http://dean.edwards.name/my/base64-ie.html

有用的链接:http: //dean.edwards.name/my/base64-ie.html

回答by Bruno

In the fiddle your blob isn't a blob, it's a string representation of hexadecimal data. Try this on a blob and your done

在小提琴中,您的 blob 不是 blob,而是十六进制数据的字符串表示形式。在 blob 上试试这个,你就完成了

var image = document.createElement('img');
let reader=new FileReader()
reader.addEventListener('loadend',()=>{
  let contents=reader.result
  image.src = contents
  document.body.appendChild(image);
})
if(blob instanceof Blob) reader.readAsDataURL(blob)

readAsDataURL give you a base64 encoded image ready for you image element () source (src)

readAsDataURL 为您提供一个 base64 编码的图像,为您准备好图像元素 () 源 (src)