This repository has been archived by the owner on Aug 4, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 12
/
make_image_csv.ts
79 lines (68 loc) · 1.84 KB
/
make_image_csv.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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import "../setup";
import path from "path";
import fs from "fs";
import glob from "glob";
import sizeOf from "image-size";
import CsvStringify from "csv-stringify";
const publicPath = path.resolve(path.join(__dirname, "..", "public"));
async function build() {
const fullPaths = getImages();
await writeCsv(fullPaths);
}
function getImages() {
let paths = [];
paths = paths.concat(getImageType("png"));
paths = paths.concat(getImageType("svg"));
paths = paths.concat(getImageType("gif"));
paths = paths.concat(getImageType("jpg"));
paths = paths.concat(getImageType("jpeg"));
paths = paths.concat(getImageType("webp"));
return paths;
}
function getImageType(extension) {
return glob.sync(path.join(publicPath, "**", `*.${extension}`));
}
async function getRow(fullPath) {
const dim = await sizeOf(fullPath);
const pathName = fullPath.replace(publicPath, "");
if (dim) {
const ratio = (dim.width * 1.0) / dim.height;
return [pathName, dim.width, dim.height, ratio];
}
return null;
}
async function writeCsv(fullPaths) {
const filename = path.join(publicPath, "images.csv");
if (fs.existsSync(filename)) {
fs.unlinkSync(filename);
}
const columns = ["path", "width", "height", "ratio"];
const fileStream = fs.createWriteStream(filename);
const csvStream = CsvStringify({ header: true, columns });
csvStream.pipe(fileStream);
for (const fullPath of fullPaths) {
console.log(fullPath);
const row = await getRow(fullPath);
if (row) {
csvStream.write(row);
}
}
// wait for the file handle to close
await new Promise((resolve) => {
fileStream.once("close", resolve);
csvStream.end();
});
}
function main() {
build().then(
() => {
process.exit(0);
},
(error) => {
console.error(`ERROR! ${error}`);
process.exit(1);
}
);
}
// run it!
main();