使用javascript从服务器加载到图像的二进制图像

我通过 XMLHttpRequest以二进制格式从我的服务器加载jpeg图像(我需要这样).它不是base64编码.

有可能把它变成一个img对象与javascript?

谢谢

解决方法

如果XMLHttpRequest的字符编码已设置为 something that won’t change the binary data,或者您已经有 set the response type,则可以通过btoa(将其放在base64中,并将其分配为数据URI)或访问.response作为二进制数据,然后运行.responseText,分别.

假设你的实例被命名为xhr,而你正在使用xhr.send之前但在xhr.open之后的charset方法

xhr.overrideMimeType("text/plain; charset=x-user-defined");

那么当你200的时候

var dataURI = 'data:image/jpeg;base64,' + btoa(xhr.responseText);

然后您可以将其设置为< img>的src.

再次假设xhr,这个时候.response方法;在.open和.send之间

xhr.responseType = "arraybuffer";

然后在200 OK

var arrayBufferView = new Uint8Array(xhr.response),// can choose 8,16 or 32 depending on how you save your images
    blob = new Blob([arrayBufferView],{'type': 'image\/jpeg'}),objectURL = window.URL.createObjectURL(blob);

然后您可以将其设置为< img>的src. Example

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...