Home > Web Front-end > JS Tutorial > How to Efficiently Convert an ArrayBuffer to a Base64 String?

How to Efficiently Convert an ArrayBuffer to a Base64 String?

Patricia Arquette
Release: 2024-12-19 10:29:14
Original
704 people have browsed it

How to Efficiently Convert an ArrayBuffer to a Base64 String?

Convert an ArrayBuffer to Base64-Encoded Strings

To efficiently transmute an ArrayBuffer into a base64 string for multipart posting, leverage this native code snippet:

function _arrayBufferToBase64( buffer ) {
    var binary = '';
    var bytes = new Uint8Array( buffer );
    var len = bytes.byteLength;
    for (var i = 0; i < len; i++) {
        binary += String.fromCharCode( bytes[ i ] );
    }
    return window.btoa( binary );
}
Copy after login

While providing an efficient native solution, consider using faster non-native implementations like this one: https://gist.github.com/958841.

Performance comparisons demonstrate a notable speed advantage for non-native methods, as highlighted in benchmarks:

  • jsperf.com/encoding-xhr-image-data/6
  • jsben.ch/wnaZC

The above is the detailed content of How to Efficiently Convert an ArrayBuffer to a Base64 String?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template