如何将图像二进制文件从 API 调用转换为 Javascript 中的数据 URI? [英] How can I convert image binary from API call to data URI in Javascript?

查看:13
本文介绍了如何将图像二进制文件从 API 调用转换为 Javascript 中的数据 URI?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的 Google API 仅将图像作为二进制数据传输.

The Google API I'm using is transmitting images only as binary data.

我完全不知道如何将其放入数据 URI 中以显示它,感谢您的帮助!

I have absolutly no idea how to put this into a data URI to display it, thanks for any help!

我正在谈论的调用是这个 API 调用.

如你所见,它说:

服务器返回照片的字节数.

The server returns bytes of the photo.

对于呼叫(它是一个扩展),我使用 chrome_ex_oauth 方法.也许我需要在标题中添加一些东西来获取真正的二进制数据,而不是现在出现的字符串......

For the call (it's an extension), I use the chrome_ex_oauth methods. Maybe I need to add something into the header to get real binary data, not string as it comes in right now...

我需要做的是将生成的二进制文件转换为数据 URI,以便我可以显示它.

What I need to do is to convert the resulting binary into data URI so I can display it.

好的,我从 XHR 请求中得到了这个

Ok, I get this out of the XHR request

现在,我不太了解二进制的东西.我假设这是以某种方式编码的二进制数据?我试图把它放到 btoa 和其他 base64 编码器中,一切都会引发错误.我试图用不同的东西覆盖 MimeType 并且响应"以一些奇怪的方式改变,但没有任何东西接受数据.

Now, I dont know binary stuff much. This is somehow encoded binary data i assume? I tried to put this into btoa and other base64 encoders, everything throws an error. I tried to overrideMimeType with different things and the "response" changed in some strange ways, but nothing accepts the data.

所以现在我有了这个代码:

So now I have this code:

var nxhr = new XMLHttpRequest();
nxhr.onreadystatechange = function (data) {
    if (nxhr.readyState == 4) {
        console.log(nxhr);
    }
};
nxhr.open(method, url, true);
nxhr.setRequestHeader('GData-Version', '3.0');
nxhr.setRequestHeader('Authorization', oauth.getAuthorizationHeader(url, method, params));
nxhr.send('Data to send');

任何人都知道如何将我无法理解的响应转换为数据 uri???

Anybody else has any idea how to get this for me not understandable response into a data uri???

感谢您的帮助

推荐答案

好的,我找到了解决方案...

Ok I found the solution...

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

之后浏览器不会触及数据.

After that the data is untouched by the browser.

Base64 = {

            // private property
            _keyStr: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",

            encodeBinary: function (input) {
                var output = "";
                var bytebuffer;
                var encodedCharIndexes = new Array(4);
                var inx = 0;
                var paddingBytes = 0;

                while (inx < input.length) {
                    // Fill byte buffer array
                    bytebuffer = new Array(3);
                    for (jnx = 0; jnx < bytebuffer.length; jnx++)
                        if (inx < input.length)
                            bytebuffer[jnx] = input.charCodeAt(inx++) & 0xff; // throw away high-order byte, as documented at: https://developer.mozilla.org/En/Using_XMLHttpRequest#Handling_binary_data
                        else
                            bytebuffer[jnx] = 0;

                    // Get each encoded character, 6 bits at a time
                    // index 1: first 6 bits
                    encodedCharIndexes[0] = bytebuffer[0] >> 2;
                    // index 2: second 6 bits (2 least significant bits from input byte 1 + 4 most significant bits from byte 2)
                    encodedCharIndexes[1] = ((bytebuffer[0] & 0x3) << 4) | (bytebuffer[1] >> 4);
                    // index 3: third 6 bits (4 least significant bits from input byte 2 + 2 most significant bits from byte 3)
                    encodedCharIndexes[2] = ((bytebuffer[1] & 0x0f) << 2) | (bytebuffer[2] >> 6);
                    // index 3: forth 6 bits (6 least significant bits from input byte 3)
                    encodedCharIndexes[3] = bytebuffer[2] & 0x3f;

                    // Determine whether padding happened, and adjust accordingly
                    paddingBytes = inx - (input.length - 1);
                    switch (paddingBytes) {
                        case 2:
                            // Set last 2 characters to padding char
                            encodedCharIndexes[3] = 64;
                            encodedCharIndexes[2] = 64;
                            break;
                        case 1:
                            // Set last character to padding char
                            encodedCharIndexes[3] = 64;
                            break;
                        default:
                            break; // No padding - proceed
                    }
                    // Now we will grab each appropriate character out of our keystring
                    // based on our index array and append it to the output string
                    for (jnx = 0; jnx < encodedCharIndexes.length; jnx++)
                        output += this._keyStr.charAt(encodedCharIndexes[jnx]);
                }
                return output;
            }
        };

mozilla 发布了一些神奇的东西,它没有让我正确编码这些东西

There is the magic stuff posted by mozilla which didnt let me encode the stuff correctly

bytebuffer[jnx] = input.charCodeAt(inx++) & 0xff

最终的代码看起来像这样......

The final code would look then like this...

oauth.authorize(function () {
    var method = "GET", params = {}, url = photo.href;

    var nxhr = new XMLHttpRequest();
    nxhr.onreadystatechange = function (data) {
        if (nxhr.readyState == 4) {
            console.log("<img src='data:image/*;base64," + Base64.encodeBinary(nxhr.response) + "' />");
        }
    };
    nxhr.open(method, url, true);
    nxhr.setRequestHeader('GData-Version', '3.0');
    nxhr.setRequestHeader('Authorization', oauth.getAuthorizationHeader(url, method, params));
    nxhr.overrideMimeType('text/plain; charset=x-user-defined'); 
});

附言如果直接将data:image/*"放入浏览器窗口,它会下载文件而无法打开它.但是如果你把它直接放到一个 img src 中,它就可以正常工作!

P.S. If you put the "data:image/*" into the browser window directly, it will download the file and would not be able to open it. But if you put it directly into an img src it works fine!

这篇关于如何将图像二进制文件从 API 调用转换为 Javascript 中的数据 URI?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆