-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
mod.ts
94 lines (83 loc) · 1.61 KB
/
mod.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
import init, {
decode as wasmDecode,
encode as wasmEncode,
source,
} from "./wasm.js";
await init(source);
type ValueOf<T> = T[keyof T];
export const ColorType = {
Grayscale: 0,
RGB: 2,
Indexed: 3,
GrayscaleAlpha: 4,
RGBA: 6,
};
export const BitDepth = {
One: 1,
Two: 2,
Four: 4,
Eight: 8,
Sixteen: 16,
};
export const Compression = {
Default: 0,
Fast: 1,
Best: 2,
Huffman: 3,
Rle: 4,
};
export const FilterType = {
NoFilter: 0,
Sub: 1,
Up: 2,
Avg: 3,
Paeth: 4,
};
export interface DecodeResult {
image: Uint8Array;
width: number;
height: number;
colorType: ValueOf<typeof ColorType>;
bitDepth: ValueOf<typeof BitDepth>;
lineSize: number;
}
export function encode(
image: Uint8Array,
width: number,
height: number,
options?: {
palette?: Uint8Array;
trns?: Uint8Array;
color?: ValueOf<typeof ColorType>;
depth?: ValueOf<typeof BitDepth>;
compression?: ValueOf<typeof Compression>;
filter?: ValueOf<typeof FilterType>;
stripAlpha?: boolean;
},
): Uint8Array {
if (options?.stripAlpha) {
image = image.filter((_, i) => (i + 1) % 4);
}
return wasmEncode(
image,
width,
height,
options?.palette,
options?.trns,
options?.color ?? ColorType.RGBA,
options?.depth ?? BitDepth.Eight,
options?.compression,
options?.filter,
);
}
export function decode(image: Uint8Array): DecodeResult {
const res = wasmDecode(image);
return {
image: new Uint8Array(res.image),
width: res.width,
height: res.height,
colorType: res.colorType,
bitDepth: res.bitDepth,
lineSize: res.lineSize,
};
}