首页 > 技术文章 > JavaScript如何转换二进制数据显示成图片

hula100 2017-08-12 16:15 原文

使用JavaScript调用API返回了二进制数据格式的图片,该如何显示到网页上?

首先,直接使用XMLHttpRequest,而不是AJAX,原因已经在前一篇文章中解释。并将responseType设置为arraybuffer

var xhr = new XMLHttpRequest();
xhr.open('GET', '/my/image/name.png', true);
xhr.responseType = 'arraybuffer';

然后,将二进制转成图片源,我从网上搜索找到以下两种方法,大家可以随意选择自己喜欢的。

方法一

var uInt8Array = new Uint8Array(xhr.response);
var i = uInt8Array.length;
var binaryString = new Array(i);
while (i--) {
    binaryString[i] = String.fromCharCode(uInt8Array[i]);
}
var data = binaryString.join('');

var imageType = xhr.getResponseHeader("Content-Type");
$('#image').attr("src", "data:" + imageType + ";base64," + data)

方法二

var imageType = xhr.getResponseHeader("Content-Type");
var blob = new Blob([xhr.response], { type: imageType });
var imageUrl = (window.URL || window.webkitURL).createObjectURL(blob);
$('#image').attr("src", imageUrl);

 

推荐阅读