This repository has been archived by the owner on May 4, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
prepareImages.js
75 lines (66 loc) · 2.52 KB
/
prepareImages.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
const fg = require("fast-glob");
const { mkdirp, removeSync } = require("fs-extra");
const sharp = require("sharp");
const inFolder = "./content/images";
const outFolder = "./public/images/responsive";
const jpg = getFiles(inFolder, "jpg");
console.log("Preparing responsive images");
removeSync(outFolder);
//---
jpg.forEach((el) => {
//---
const img = sharp(el.fullpath);
recodeImage(img, el);
resizeImage(img, 300, el);
resizeImage(img, 400, el);
resizeImage(img, 800, el);
resizeImage(img, 1200, el);
resizeImage(img, 1920, el);
});
function resizeImage(img, width, inFile) {
const f = `${outFolder}/${width}`;
mkdirp(f, { recursive: true });
const outputFile = inFile.fullpath.replace(inFolder, f);
const outputFileAvif = outputFile.replace("jpg", "avif");
const outputFileWebP = outputFile.replace("jpg", "webp");
img.resize(width, width, {
fit: sharp.fit.inside,
// withoutEnlargement: true,
});
// for dev purposes, you might want to integrate image width into actual image
// to quickly see which one gets used by the browser
//
// const svg = new Buffer.from(`<svg height="${width / 2}" width="${width / 2}"> <text x="0" y="${width / 2}" font-size="${width / 5}" fill="#4400ff">${width}</text> </svg>`);
// img.composite([{ input: svg, gravity: "center" }]).toBuffer();
//
img.clone().toFormat("jpeg").jpeg({ quality: 65 }).toFile(outputFile);
img.clone().toFormat("avif").avif({ quality: 55 }).toFile(outputFileAvif);
img.clone().toFormat("webp").webp({ quality: 65 }).toFile(outputFileWebP);
}
function recodeImage(img, inFile) {
const f = outFolder;
mkdirp(f);
const outputFile = inFile.fullpath.replace(inFolder, f);
const outputFileAvif = outputFile.replace("jpg", "avif");
const outputFileWebP = outputFile.replace("jpg", "webp");
img.clone().toFormat("jpeg").jpeg({ quality: 65 }).toFile(outputFile);
img.clone().toFormat("avif").avif({ quality: 55 }).toFile(outputFileAvif);
img.clone().toFormat("webp").webp({ quality: 65 }).toFile(outputFileWebP);
}
function getFiles(inFolder, extension) {
const entries = fg.sync(`${inFolder}/**/*.${extension}`, { dot: true });
const filesObject = entries.map((file) => {
const regexp = /^(.*[\\\/])(.*)$/;
const match = regexp.exec(file);
const nameExt = match[2].split(".");
return {
fullpath: file,
filepath: match[1],
filename: match[2],
name: nameExt[0],
ext: nameExt[1],
dirname: regexp.exec(match[1].substring(0, match[1].length - 1))[2],
};
});
return filesObject;
}