JavaScript 如何转换二进制数据显示成图片

来源 https://www.cnblogs.com/hula100/p/7350628.html

首先,直接使用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);
 
 
 

首先,直接使用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);

猜你喜欢

转载自www.cnblogs.com/yuhaipeng/p/12743118.html