-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.js
68 lines (64 loc) · 1.49 KB
/
utils.js
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
const sharp = require("sharp");
const screenshot = require("screenshot-desktop");
/**
* 屏幕截图
* @returns {Promise<Buffer>}
*/
function screenShot() {
return new Promise((resolve, reject) => {
let t = Date.now();
screenshot({ format: "png" })
.then((img) => {
console.log("screenshot time:", Date.now() - t);
resolve(img);
})
.catch((err) => {
reject(err);
});
});
}
/**
* 裁剪图片
* @param {*} source string | Buffer | Stream | File | Array<File> | Array<Buffer> | Array<Stream>
* @param {*} x number
* @param {*} y number
* @param {*} width number
* @param {*} height number
* @param {*} devicePixelRatio number
* @returns {Promise<Buffer>}
*/
function crop(source, x, y, width, height, devicePixelRatio = 1) {
return new Promise((resolve, reject) => {
// 裁剪前先将坐标和尺寸乘以设备像素比,计算出实际图像的坐标和尺寸
x *= devicePixelRatio;
y *= devicePixelRatio;
width *= devicePixelRatio;
height *= devicePixelRatio;
sharp(source)
.extract({
left: parseInt(x),
top: parseInt(y),
width: parseInt(width),
height: parseInt(height),
})
.toBuffer()
.then((data) => {
resolve(data);
})
.catch((err) => {
reject(err);
});
});
}
/**
* 获取项目根目录
* @returns {string}
*/
function getProjectRoot() {
return __dirname;
}
module.exports = {
screenShot,
crop,
getProjectRoot,
};