forked from catdad-experiments/heic-convert
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.js
More file actions
57 lines (48 loc) · 1.5 KB
/
Copy pathindex.js
File metadata and controls
57 lines (48 loc) · 1.5 KB
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
const jpegJs = require('jpeg-js');
const { PNG } = require('pngjs');
const decode = require('@freiraum/heic-decode');
const to = {
JPEG: ({ data, width, height, quality }) => jpegJs.encode({ data, width, height }, quality).data,
PNG: ({ data, width, height }) => {
const png = new PNG({ width, height });
png.data = data;
return PNG.sync.write(png, {
width: width,
height: height,
deflateLevel: 9,
deflateStrategy: 3,
filterType: -1,
colorType: 6,
inputHasAlpha: true
});
}
};
const convertImage = async ({ image, format, quality }) => {
return await to[format]({
width: image.width,
height: image.height,
data: Buffer.from(image.data),
quality: Math.floor(quality * 100)
});
};
const convert = async ({ buffer, format, quality, all }) => {
if (!to[format]) {
throw new Error(`output format needs to be one of [${Object.keys(to)}]`);
}
if (!all) {
const image = await decode({ buffer });
return await convertImage({ image, format, quality });
}
const images = await decode.all({ buffer });
return images.map(image => {
return {
convert: async () => await convertImage({
image: await image.decode(),
format,
quality
})
};
});
};
module.exports = async ({ buffer, format, quality = 0.92 }) => await convert({ buffer, format, quality, all: false });
module.exports.all = async ({ buffer, format, quality = 0.92 }) => await convert({ buffer, format, quality, all: true });