-
Notifications
You must be signed in to change notification settings - Fork 1
/
img.11ty.js
91 lines (77 loc) · 2.11 KB
/
img.11ty.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
const path = require('path');
const util = require('util');
const glob = require('glob');
const sharp = require('sharp');
const mkdirp = require('mkdirp');
const { options } = require('cssesc');
const outputPath = 'dist/_assets/img/';
const resizeConf = {
sizes: [
{
width: 320,
rename: { suffix: '-320' },
}, {
width: 550,
rename: { suffix: '-550' },
}
],
jpegOptions: {
quality: 80,
progressive: true,
withMetadata: false,
force: false
// withoutEnlargement: true,
// errorOnUnusedImage: false,
// errorOnEnlargement: false
},
pngOptions: {
compressionLevel: 8,
force: false
}
};
module.exports = class {
async data() {
const filePath = path.join(__dirname, `/img/`);
return {
permalink: `/_assets/img/images.json`,
eleventyExcludeFromCollections: true,
filePath,
}
}
async loadImages(imgFolder) {
const cwd = path.resolve(imgFolder.file);
const getImages = util.promisify(glob);
const processedImages = [];
const imgs = await getImages('**/*(*.jpg|*.png|*.gif)', { cwd: cwd });
imgs.forEach(function (img) {
const ext = path.extname(img);
const base = path.basename(img, ext);
const dir = path.dirname(img);
mkdirp.sync(path.join(outputPath, dir));
let passThroughImg = sharp(imgFolder.file + img);
passThroughImg.toFile(path.join(outputPath, dir, base + ext));
resizeConf.sizes.forEach(function (size) {
const newPath = path.join(outputPath, dir, base + size.rename.suffix + ext);
const image = sharp(imgFolder.file + img);
image
.jpeg( resizeConf.jpegOptions )
.png( resizeConf.pngOptions )
.resize({
width: size.width,
withoutEnlargement: true,
kernel: 'lanczos2'
})
.toFile(newPath);
});
processedImages.push(img);
});
return JSON.stringify(processedImages, null, '\t');
}
async render({ filePath }) {
try {
return await this.loadImages({ file: filePath });
} catch (err) {
throw new Error(err);
}
}
}