【发布时间】:2012-11-28 07:02:57
【问题描述】:
我正在通过 XMLHttpRequest 从我的服务器以二进制格式加载 jpeg 图像(我需要这种方式)。它不是 base64 编码的。
是否可以用 javascript 将其转为 img 对象?
谢谢
【问题讨论】:
标签: javascript html dom binary xmlhttprequest
我正在通过 XMLHttpRequest 从我的服务器以二进制格式加载 jpeg 图像(我需要这种方式)。它不是 base64 编码的。
是否可以用 javascript 将其转为 img 对象?
谢谢
【问题讨论】:
标签: javascript html dom binary xmlhttprequest
如果XMLHttpRequest 的字符编码已设置为something that won't change the binary data,或者您已设置set the response type,则可以运行.responseText 到btoa(将其放入base64 并让您将其分配为数据 URI) 或访问 .response 分别获取二进制数据。
假设您的实例名为xhr,并且您在xhr.send 之前但在xhr.open 之后使用charset 方法
xhr.overrideMimeType("text/plain; charset=x-user-defined");
那么当你是200 OK
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
【讨论】:
btoa(xhr.responseText) 不断返回Error: INVALID_CHARACTER_ERR: DOM Exception 5。我找不到为什么会发生这种情况。对于 IE7/IE8... 我将不得不制作一个 Flash 对象来处理它 grrr
btoa 有一些 bugs(同样/类似的也适用于 webkit),我将使用 ArrayBuffer -> @987654348 更新答案@ -> 通过 URL.createObjectURL 方法,在我看来这比通过 FileReader 稍微好一点,但仍然不如 btoa 好。跨度>