forked from lobehub/lobe-chat
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathimageToBase64.ts
62 lines (55 loc) · 1.33 KB
/
imageToBase64.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
export const imageToBase64 = ({
size,
img,
type = 'image/webp',
}: {
img: HTMLImageElement;
size: number;
type?: string;
}) => {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d') as CanvasRenderingContext2D;
let startX = 0;
let startY = 0;
if (img.width > img.height) {
startX = (img.width - img.height) / 2;
} else {
startY = (img.height - img.width) / 2;
}
canvas.width = size;
canvas.height = size;
ctx.drawImage(
img,
startX,
startY,
Math.min(img.width, img.height),
Math.min(img.width, img.height),
0,
0,
size,
size,
);
return canvas.toDataURL(type);
};
export const imageUrlToBase64 = async (
imageUrl: string,
): Promise<{ base64: string; mimeType: string }> => {
try {
const res = await fetch(imageUrl);
const blob = await res.blob();
const arrayBuffer = await blob.arrayBuffer();
const base64 =
typeof btoa === 'function'
? btoa(
new Uint8Array(arrayBuffer).reduce(
(data, byte) => data + String.fromCharCode(byte),
'',
),
)
: Buffer.from(arrayBuffer).toString('base64');
return { base64, mimeType: blob.type };
} catch (error) {
console.error('Error converting image to base64:', error);
throw error;
}
};