微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用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

原文地址:https://www.jb51.cc/js/151920.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐