-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
56 lines (48 loc) · 1.33 KB
/
index.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
import tinify from 'tinify';
const sizeOf = require('image-size');
const bufferSizeOf = require('buffer-image-size');
export interface ITinifyAdapterParams {
tinifyKey: string;
method: string;
}
interface IResizeParams {
width: number;
height: number;
options: any;
}
export const responsiveLoaderTinifyAdapter = ({
tinifyKey,
method = 'scale'
}: ITinifyAdapterParams) => {
tinify.key = tinifyKey;
return (imagePath: string) => {
const image = tinify.fromFile(imagePath);
const originalSize = sizeOf(imagePath);
return {
metadata: () => Promise.resolve(originalSize),
resize: ({ width, options }: IResizeParams) =>
new Promise((resolve, reject) => {
const resizeMethod = options.method || method;
const newHeight = Math.round(
originalSize.height * (width / originalSize.width)
);
const resized = image.resize({
method: resizeMethod,
width,
...(resizeMethod !== 'scale' ? { height: newHeight } : {})
});
resized.toBuffer((err, data) => {
if (err) {
reject(err);
} else {
resolve({
data,
width,
height: bufferSizeOf(data).height
});
}
});
})
};
};
};