【问题标题】:Binary image loaded from server to image with javascript使用javascript从服务器加载二进制图像到图像
【发布时间】:2012-11-28 07:02:57
【问题描述】:

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

是否可以用 javascript 将其转为 img 对象?

谢谢

【问题讨论】:

    标签: javascript html dom binary xmlhttprequest


    【解决方案1】:

    如果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

    【讨论】:

    • 这称为内嵌图像。请注意,IE8 仅支持小于 32 KB 的内联图像(对于 base64 编码数据,因此源图像必须小于 24 KB),而 IE7 及更早版本根本不支持内联图像(如果这很重要) )。
    • 试过了,但btoa(xhr.responseText) 不断返回Error: INVALID_CHARACTER_ERR: DOM Exception 5。我找不到为什么会发生这种情况。对于 IE7/IE8... 我将不得不制作一个 Flash 对象来处理它 grrr
    • @Marc 发生这种情况是因为 btoa 有一些 bugs(同样/类似的也适用于 webkit),我将使用 ArrayBuffer -> @987654348 更新答案@ -> 通过 URL.createObjectURL 方法,在我看来这比通过 FileReader 稍微好一点,但仍然不如 btoa 好。跨度>
    • 至于这个方法的兼容性,looks likeIE10+
    猜你喜欢
    • 2014-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多