Skip to content
This repository was archived by the owner on Jul 26, 2025. It is now read-only.

Commit 2e7515a

Browse files
committed
feat: add base64 string encoding
1 parent bd5cc06 commit 2e7515a

File tree

2 files changed

+53
-0
lines changed

2 files changed

+53
-0
lines changed

src/save/encodeBase64.ts

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
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+

src/save/index.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,3 +3,4 @@ export * from './encodePng.js';
33
export * from './encodeJpeg.js';
44
export * from './write.js';
55
export * from './writeCanvas.js';
6+
export * from './encodeBase64.js';

0 commit comments

Comments
 (0)