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