如何从响应解析为字符串的base64二进制图像? [英] How to parse into base64 string the binary image from response?

查看:1217
本文介绍了如何从响应解析为字符串的base64二进制图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从我的REST API解析请求的图像到的base64字符串。

首先...我想,这将是很容易,只要使用 window.btoa()功能这一目标。

当我尝试做我的应用程序该部分:

  .done(功能(响应,位置){
    VAR纹理=新的图像();
    texture.src =数据:图像/ PNG; BASE64,+ window.btoa(响应);

我已经得到了一个错误:未捕获InvalidCharacterError:未能执行的'窗口''BTOA':字符串是EN codeD包含字符Latin1的范围之外 <。 / p>

当我读到这里:<一href=\"http://stackoverflow.com/questions/9786508/javascript-atob-returning-string-contains-an-invalid-character\">javascript ATOB返回字符串中包含无效字符'

是因为在响应换行符的问题,这就是为什么 window.btoa()失败。
当然任何二进制图像格式将有换行符...但是从建议上面的链接是删除/替换这些字符 - 对我来说是一个糟糕的建议,因为如果删除/替换二进制图像,它只是将一些字符损坏。

当然,可能的选择涉及到API的设计:
  - 添加一些功能,它返回的base64再presentation
  - 添加一些功能,返回URL的图像

如果我不会修,但须从服务器返回的base64再presentation,但我不喜欢这样的方式。

确实存在一些方法来解决我的问题与响应处理二进制图像,因为它上面显示的屏幕截图中的一部分,不是吗?


解决方案

我想你击中了问题的一部分是, jQuery.ajax 做的的原生支持XHR2 BLOB / arraybuffer类型,可以很好地处理二进制数据(请参阅阅读使用jQuery.ajax )二进制文件。

如果您使用 xhr.responseType ='arraybuffer'本机XHR对象,然后读取响应阵列,并将其转换为Base64,你会得到你想要的东西

下面是对我工作的解决方案:

\r
\r

// http://www.henryalgus.com/reading-binary-files - 使用-的jQuery的Ajax /\r
功能fetchBlob(URI,回调){\r
  VAR XHR =新XMLHtt prequest();\r
  xhr.open(GET,URI,真正的);\r
  xhr.responseType ='arraybuffer';\r
\r
  xhr.onload =功能(E){\r
    如果(this.status == 200){\r
      VAR BLOB = this.response;\r
      如果(回调){\r
        回调(BLOB);\r
      }\r
    }\r
  };\r
  xhr.send();\r
};\r
\r
fetchBlob('https://i.imgur.com/uUGeiSFb.jpg',函数(BLOB){\r
  //数组缓冲区为Base64:\r
  无功海峡= BTOA(String.fromChar code.apply(空,新Uint8Array(BLOB)));\r
\r
  的console.log(STR);\r
  //或者:'&LT; IMG SRC =数据:图像/ JPEG; BASE64,+ STR +'&GT;'\r
});

\r

\r
\r

https://jsfiddle.net/oy1pk8r3/2/

生成的base64 EN codeD控制台输出: / 9J / 4AAQSkZJRgABAQEASABIAAD / 2wBDAAIBAQIBAQICAgICAgICAw .....

I want to parse the requested image from my REST API into base64 string.

Firstly... I thought, it would be easy, just to use window.btoa() function for this aim.

When I try to do it in such part of my application:

.done( function( response, position ) {
    var texture = new Image();
    texture.src = "data:image/png;base64," + window.btoa( response ); 

I've got the next error: Uncaught InvalidCharacterError: Failed to execute 'btoa' on 'Window': The string to be encoded contains characters outside of the Latin1 range.

As I read here: javascript atob returning 'String contains an invalid character'

The issue occurs because of newlines in the response and that's why window.btoa() failed. Any binary image format of course will have newlines... But as from the link above the suggestion was to remove/replace those characters - is a bad suggestion for me, because if to remove/replace some characters from binary image it just will be corrupted.

Of course, the possible alternatives relate to the API design: - to add some function, which return base64 representation - to add some function, which return url to the image

If I won't repair it, I shall return base64 representation from the server, but I don't like such a way.

Does exist some way to solve my problem with the handling binary image from response, as it's shown above in the part of screenshot, doesn't it?

解决方案

I think part of the problem you're hitting is that jQuery.ajax does not natively support XHR2 blob/arraybuffer types which can nicely handle binary data (see Reading binary files using jQuery.ajax).

If you use a native XHR object with xhr.responseType = 'arraybuffer', then read the response array and convert it to Base64, you'll get what you want.

Here's a solution that works for me:

// http://www.henryalgus.com/reading-binary-files-using-jquery-ajax/
function fetchBlob(uri, callback) {
  var xhr = new XMLHttpRequest();
  xhr.open('GET', uri, true);
  xhr.responseType = 'arraybuffer';

  xhr.onload = function(e) {
    if (this.status == 200) {
      var blob = this.response;
      if (callback) {
        callback(blob);
      }
    }
  };
  xhr.send();
};

fetchBlob('https://i.imgur.com/uUGeiSFb.jpg', function(blob) {
  // Array buffer to Base64:
  var str = btoa(String.fromCharCode.apply(null, new Uint8Array(blob)));

  console.log(str);
  // Or: '<img src="data:image/jpeg;base64,' + str + '">'
});

https://jsfiddle.net/oy1pk8r3/2/

Produces base64 encoded console output: /9j/4AAQSkZJRgABAQEASABIAAD/2wBDAAIBAQIBAQICAgICAgICAw.....

这篇关于如何从响应解析为字符串的base64二进制图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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