@@ -10,40 +10,9 @@ import type { ImageFormat } from './encode.js';
1010 * @returns base64 string.
1111 */
1212export function encodeBase64 ( image : Image , format : ImageFormat ) {
13- const isNode =
14- typeof window === 'undefined' && typeof document === 'undefined' ;
15- if ( isNode ) {
16- return encodeBase64InNode ( image , format ) ;
17- } else {
18- return encodeBase64InBrowser ( image , format ) ;
19- }
13+ const buffer = encode ( image , { format } ) ;
14+ const binaryString = new TextDecoder ( 'latin1' ) . decode ( Uint8Array . from ( buffer ) ) ;
15+ const base64String = btoa ( binaryString ) ;
16+ return `data:image/${ format } ;base64,${ base64String } ` ;
2017}
2118
22- /**
23- * Converts image into a base64 URL string in NodeJs.
24- * @param image - Image to get base64 encoding from.
25- * @param format - Image format.
26- * @returns base64 string.
27- */
28- function encodeBase64InNode ( image : Image , format : ImageFormat ) {
29- const encodedData = encode ( image , { format } ) ;
30- return `data:image/${ format } ;base64,${ Buffer . from ( encodedData ) . toString (
31- 'base64' ,
32- ) } `;
33- }
34- /**
35- * Converts image into a base64 URL string in browser.
36- * @param image - Image to get base64 encoding from.
37- * @param format - Image format.
38- * @returns base64 string.
39- */
40- function encodeBase64InBrowser ( image : Image , format : ImageFormat ) {
41- const buffer = encode ( image , { format } ) ;
42- let binaryString = '' ;
43- for ( const el of buffer ) {
44- binaryString += String . fromCodePoint ( el ) ;
45- }
46- const base64String = btoa ( binaryString ) ;
47- const dataURL = `data:image/${ format } ;base64,${ base64String } ` ;
48- return dataURL ;
49- }
0 commit comments