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

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

问题描述

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



我绝对不知道如何将其放入数据URI中以显示它,谢谢你的帮助!



我所说的电话是

正如你所看到的,它说:


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

对于通话(这是一个扩展) ,我使用chrome_ex_oauth方法。也许我需要在头文件中添加一些东西来获得真正的二进制数据,而不是字符串,因为它现在正在进入...



我需要做的是将将二进制数据导入到数据URI中,以便我可以显示它。






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





现在,我不太了解二进制文件。这是我假设的编码二进制数据?我试图把它放到btoa和其他base64编码器中,一切都会引发错误。
我尝试用不同的东西来覆盖MIME类型,而响应以某种奇怪的方式进行了修改,但没有任何东西可以接受数据。

所以现在我有这样的代码:

  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('发送数据');

其他人有任何想法如何得到这个对我来说不可理解的响应数据uri?



感谢您的帮助

解决方案

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

首先,请求必须覆盖returend Type到x-user-defined



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

之后,浏览器不会触动数据。



使用以下Base64编码器



  Base64 = {

//私有财产
_keyStr:ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 + / =,

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

while(inx< input.length){
//填充字节缓冲区数组
bytebuffer = new Array(3);
for(jnx = 0; jnx< bytebuffer.length; jnx ++)
if(inx< input.length)
bytebuffer [jnx] = input.charCodeAt(inx ++)& 0xFF的; //扔掉高位字节,如下所示:https://developer.mozilla.org/En/Using_XMLHttpRequest#Handling_binary_data
else
bytebuffer [jnx] = 0;

//获取每个编码字符,一次6位
//索引1:前6位
encodedCharIndexes [0] = bytebuffer [0]>> 2;
//索引2:第二个6位(来自输入字节1的2个最低有效位+来自字节2的4个最高有效位)
encodedCharIndexes [1] =((bytebuffer [0]& 0x3)< ;< 4)| (bytebuffer [1]>> 4);
//索引3:第三个6位(来自输入字节2的4个最低有效位+来自字节3的2个最高有效位)
encodedCharIndexes [2] =((bytebuffer [1]& 0x0f)< ;< 2)| (bytebuffer [2]>> 6);
//索引3:前6位(来自输入字节3的6个最低有效位)
encodedCharIndexes [3] = bytebuffer [2]& 0x3F的;

//确定填充是否发生,并相应地进行调整
paddingBytes = inx - (input.length - 1);
switch(paddingBytes){
case 2:
//设置最后2个字符为填充字符
encodedCharIndexes [3] = 64;
encodedCharIndexes [2] = 64;
休息;
案例1:
//设置最后一个字符为填充char
encodedCharIndexes [3] = 64;
休息;
默认值:
break; //没有填充 - 继续
}
//现在,我们将根据索引数组从我们的键串
//中获取每个适当的字符,并将其附加到输出字符串
for(jnx = 0; jnx< encodedCharIndexes.length; jnx ++)
output + = this._keyStr.charAt(encodedCharIndexes [jnx]);
}
返回输出;
}
};

有mozilla发布的魔术材料,它没有让我正确地编码材料

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

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

  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中,它就可以正常工作!


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

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

The call I'm talking about is this API call.

As you can see, it says:

The server returns bytes of the photo.

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...

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


Ok, I get this out of the XHR request

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');

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

Thanks for any help

解决方案

Ok I found the solution...

First of all, the request must override the returend Type into x-user-defined

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

After that the data is untouched by the browser.

Use the following Base64 encoder

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;
            }
        };

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'); 
});

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天全站免登陆