简体   繁体   English

如何将响应中的二进制图像解析为 base64 字符串?

[英]How to parse into base64 string the binary image from response?

I want to parse the requested image from my REST API into base64 string.我想将 REST API 中请求的图像解析为 base64 字符串。

在此处输入图片说明

Firstly... I thought, it would be easy, just to use window.btoa() function for this aim.首先......我认为,这很容易,只需为此目的使用window.btoa()函数。

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.我遇到了下一个错误:未捕获的 InvalidCharacterError:无法在 'Window' 上执行 'btoa':要编码的字符串包含超出 Latin1 范围的字符。

As I read here: javascript atob returning 'String contains an invalid character'正如我在这里读到的: javascript atob 返回“字符串包含无效字符”

The issue occurs because of newlines in the response and that's why window.btoa() failed.出现此问题是由于newlines in the responsenewlines in the response ,这就是window.btoa()失败的原因。 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当然,可能的替代方案与 API 设计有关: - 添加一些函数,返回 base64 表示 - 添加一些函数,将 url 返回到图像

If I won't repair it, I shall return base64 representation from the server, but I don't like such a way.如果我不修复它,我将从服务器返回base64表示,但我不喜欢这种方式。

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 ).我认为您遇到的部分问题是jQuery.ajax本身支持可以很好地处理二进制数据的 XHR2 blob/arraybuffer 类型(请参阅使用 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.如果您使用带有xhr.responseType = 'arraybuffer'的原生 XHR 对象,然后读取响应数组并将其转换为 Base64,您将得到您想要的。

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/ https://jsfiddle.net/oy1pk8r3/2/

Produces base64 encoded console output: /9j/4AAQSkZJRgABAQEASABIAAD/2wBDAAIBAQIBAQICAgICAgICAw.....生成 base64 编码的控制台输出: /9j/4AAQSkZJRgABAQEASABIAAD/2wBDAAIBAQIBAQICAgICAgICAw.....

instead of looping through the blob with _arrayBufferToBase64(), use apply() to do the conversion, it's 30 times faster in my browser and is more concise不是使用 _arrayBufferToBase64() 循环遍历 blob,而是使用 apply() 进行转换,它在我的浏览器中快了 30 倍并且更简洁

 // 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) { var str = String.fromCharCode.apply(null, new Uint8Array(blob)); console.log(str); // the base64 data: image is then // '<img src="data:image/jpeg;base64,' + btoa(str) + '" />' });

Im guessing to use escape on the string before you pass it to the function, without the API call I can't test myself.我猜在将字符串传递给函数之前在字符串上使用escape符,如果没有 API 调用,我无法测试自己。

test测试

encodeURI("testñ$☺PNW¢=")

returns返回

"test%C3%B1$%E2%98%BAPNW%C2%A2="

It just escapes all the characters, it should escape all the illegal characters in the string它只是转义所有字符,它应该转义字符串中的所有非法字符

test测试

encodeURI("¶!┼Æê‼_ðÄÄ┘Ì+\+,o▬MBc§yþó÷ö")

returns返回

"%C2%B6!%E2%94%BC%C3%86%C3%AA%E2%80%BC_%C3%B0%C3%84%C3%84%E2%94%98%C3%8C++,o%E2%96%ACMBc%C2%A7y%C3%BE%C3%B3%C3%B7%C3%B6"

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURI https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURI

The issue you're encountering is that the response is being considered a Unicode String.您遇到的问题是响应被视为 Unicode 字符串。 See the section on Unicode Strings here: window.btoa请参阅此处的 Unicode 字符串部分: window.btoa

Several solutions are offered in this post这篇文章提供了几种解决方案

Long story short this looks like someone read the image with readAsText() which mangles ("interprets") binary into utf8, instead of utf16. 长话短说,这看起来像是有人用readAsText()读取图像,该图像将(“解释”)二进制文件转换为utf8而不是utf16。 You need to get the server to return the data in arraybuffer or blob format ideally, or even base64, these preserve binary. 您需要让服务器以理想的状态以arraybuffer或blob格式,甚至以base64返回数据,这些保留二进制文件。

Long version with snippet. 带摘录的长版。 (those question marks symbols in the snippet show the lost information, compare it to the binary where they are not question marks in utf16): https://stackoverflow.com/a/56523118/2962797 (代码段中的那些问号符号会显示丢失的信息,请将其与不是utf16中的问号的二进制文件进行比较): https ://stackoverflow.com/a/56523118/2962797

Try this on its working well .试试这个,让它运行良好 please try once.请尝试一次。 @user2402179 @用户2402179

  $.ajax({
    type: 'GET',
    url: baseUrl",
    dataType: 'binary',
    xhr() {
      let myXhr = jQuery.ajaxSettings.xhr();
      myXhr.responseType = 'blob';
      return myXhr;
    },
    headers: {'Authorization': 'Bearer '+token}      
    
}).then((response) => {
    // response is a Blob
    return new Promise((resolve, reject) => {
      let reader = new FileReader();
      reader.addEventListener('load', () => {
        $('#theDiv').append('<img src="' +reader.result+ '" />')
        resolve(reader.result);
      }, false);
      reader.addEventListener('error', () => {
        reject(reader.error);
      }, false);
      reader.readAsDataURL(response);
    });
  });

Base 64 Image 数据对我有用

<img src="data:image/png;base64,' + responce + '" />

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 从FilePathResult ASP.net MVC发送的http响应将二进制图像数据转换为base64字符串 - convert binary image data to base64 string from http response sent by FilePathResult ASP.net MVC 如何使用数据库中的base64字符串显示图像 - How to use base64 string from database to display an image 来自 base64 字符串的 Javascript 图像 - Javascript image from base64 string Phonegap - 如何从base64字符串生成图像文件? - Phonegap - How to generate image file from base64 string? Vue.js 不使用 base64 或来自 Express API 响应的二进制数据渲染图像 - Vue js not rendering image with base64 or binary data from Express API response 如何将PNG图像二进制字符串转换为base64而不将其写入磁盘? - How to convert PNG image binary string to base64 without writing it to disk? 如何在Angular6中压缩Base64 /二进制图像? - How to compress Base64/Binary image in Angular6? 如何 base64 在 JS 中编码二进制图像以供浏览器显示 - How to base64 encode binary image in JS for browser showing 如何将图像数据响应转换为图像 base64? - How to convert image data response to Image base64? 如何处理以base64编码的字符串中的二进制内容? - How to handle binary contents in a base64 encoded string?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM