1
+ // Converts an ArrayBuffer directly to base64, without any intermediate 'convert to string then
2
+ // use window.btoa' step. According to my tests, this appears to be a faster approach:
3
+ // http://jsperf.com/encoding-xhr-image-data/5
4
+
5
+ function base64ArrayBuffer ( arrayBuffer ) {
6
+ var base64 = ''
7
+ var encodings = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
8
+
9
+ var bytes = new Uint8Array ( arrayBuffer )
10
+ var byteLength = bytes . byteLength
11
+ var byteRemainder = byteLength % 3
12
+ var mainLength = byteLength - byteRemainder
13
+
14
+ var a , b , c , d
15
+ var chunk
16
+
17
+ // Main loop deals with bytes in chunks of 3
18
+ for ( var i = 0 ; i < mainLength ; i = i + 3 ) {
19
+ // Combine the three bytes into a single integer
20
+ chunk = ( bytes [ i ] << 16 ) | ( bytes [ i + 1 ] << 8 ) | bytes [ i + 2 ]
21
+
22
+ // Use bitmasks to extract 6-bit segments from the triplet
23
+ a = ( chunk & 16515072 ) >> 18 // 16515072 = (2^6 - 1) << 18
24
+ b = ( chunk & 258048 ) >> 12 // 258048 = (2^6 - 1) << 12
25
+ c = ( chunk & 4032 ) >> 6 // 4032 = (2^6 - 1) << 6
26
+ d = chunk & 63 // 63 = 2^6 - 1
27
+
28
+ // Convert the raw binary segments to the appropriate ASCII encoding
29
+ base64 += encodings [ a ] + encodings [ b ] + encodings [ c ] + encodings [ d ]
30
+ }
31
+
32
+ // Deal with the remaining bytes and padding
33
+ if ( byteRemainder == 1 ) {
34
+ chunk = bytes [ mainLength ]
35
+
36
+ a = ( chunk & 252 ) >> 2 // 252 = (2^6 - 1) << 2
37
+
38
+ // Set the 4 least significant bits to zero
39
+ b = ( chunk & 3 ) << 4 // 3 = 2^2 - 1
40
+
41
+ base64 += encodings [ a ] + encodings [ b ] + '=='
42
+ } else if ( byteRemainder == 2 ) {
43
+ chunk = ( bytes [ mainLength ] << 8 ) | bytes [ mainLength + 1 ]
44
+
45
+ a = ( chunk & 64512 ) >> 10 // 64512 = (2^6 - 1) << 10
46
+ b = ( chunk & 1008 ) >> 4 // 1008 = (2^6 - 1) << 4
47
+
48
+ // Set the 2 least significant bits to zero
49
+ c = ( chunk & 15 ) << 2 // 15 = 2^4 - 1
50
+
51
+ base64 += encodings [ a ] + encodings [ b ] + encodings [ c ] + '='
52
+ }
53
+
54
+ return base64
55
+ }
0 commit comments