-
Notifications
You must be signed in to change notification settings - Fork 0
/
convert.ts
65 lines (50 loc) · 2.09 KB
/
convert.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
63
64
65
type ImageVisual = HTMLCanvasElement | CanvasRenderingContext2D | HTMLImageElement | string;
const convertSourceVisualToImageData = async (visual: ImageVisual): Promise<ImageData> => {
if (visual instanceof HTMLCanvasElement) return convertCanvas(visual);
if (visual instanceof CanvasRenderingContext2D) return convertContext(visual);
if (visual instanceof HTMLImageElement) return await convertImage(visual);
if (typeof visual === 'string') return await convertFilePath(visual);
}
const convertContext = (visual: CanvasRenderingContext2D): ImageData => {
return visual.getImageData(0, 0, visual.canvas.width, visual.canvas.height);
}
const convertCanvas = (canvas: HTMLCanvasElement): ImageData => {
const ctx = canvas.getContext('2d');
const data = ctx.getImageData(0, 0, canvas.width, canvas.height)
return data;
}
const convertFilePath = async (imagePath: string, baseImagePath: string = ''): Promise<ImageData> => {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
const img = new Image();
img.decoding = 'sync';
if (imagePath) {
img.src = baseImagePath + imagePath + '?_=' + Math.random();
try {
await img.decode();
} catch {
console.warn(`Image could not be decoded, check image src: ${img.src}`)
}
}
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img, 0, 0);
return ctx.getImageData(0, 0, img.width, img.height);
}
const convertImage = async (image: HTMLImageElement): Promise<ImageData> => {
const canvas = document.createElement('canvas');
image.decoding = 'sync';
if (image.src) {
try {
await image.decode();
} catch {
console.warn(`Image could not be decoded, check image src: ${image.src}`)
}
}
canvas.width = image.width;
canvas.height = image.height;
const ctx = canvas.getContext('2d');
ctx.drawImage(image, 0, 0);
return ctx.getImageData(0, 0, image.width, image.height);
}
export { convertSourceVisualToImageData, ImageVisual };