Skip to content

Commit 316bbef

Browse files
author
Simon he
committed
chore: add toBase64
1 parent 5eb3594 commit 316bbef

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

src/toBase64.ts

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
import { FileType } from './types'
2+
export async function toBase64(o: File | string, type: FileType = 'url') {
3+
if (type === 'file' || type === 'blob')
4+
return await fileToBase64(o as File | Blob)
5+
else if (type === 'url')
6+
return await urlToBase64(o as string)
7+
}
8+
9+
export function fileToBase64(file: File | Blob) {
10+
return new Promise((resolve, reject) => {
11+
let reader = new FileReader();
12+
reader.readAsDataURL(file)
13+
reader.onload = function (e) {
14+
resolve(e?.target?.result)
15+
}
16+
})
17+
}
18+
19+
export function urlToBase64(url: string) {
20+
return new Promise((resolve, reject) => {
21+
const canvas: HTMLCanvasElement = document.createElement('canvas'),
22+
ctx = canvas.getContext('2d'),
23+
img = new Image;
24+
img.crossOrigin = 'Anonymous';
25+
img.src = url + "?timeStamp=" + new Date().getTime();
26+
img.onload = function () {
27+
ctx?.drawImage(img, 0, 0, canvas.width = img.width, canvas.height = img.height);
28+
resolve(canvas.toDataURL())
29+
};
30+
})
31+
}

0 commit comments

Comments
 (0)