kollagen/cli/main.ts

102 lines
No EOL
2.8 KiB
TypeScript

import { parse } from "https://deno.land/std@0.106.0/flags/mod.ts";
import { createCanvas } from "https://deno.land/x/canvas@v1.3.0/mod.ts";
import {
collageModeType,
DisplayCollageModeType,
displayCollageModeType,
} from "../src/common/collages.ts";
import { denoCollageModes, ProxyImage } from "./collages.ts";
import { CollageConfig } from "../src/common/types.ts";
import { choice, shuffle } from "../src/common/utils.ts";
import { walkSync } from "https://deno.land/std@0.107.0/fs/mod.ts";
import { parseCollageModes, parseDisplayCollageModes } from "./util.ts";
const args = parse(Deno.args, {
alias: {
w: "width",
h: "height",
o: "output",
m: "mode",
},
boolean: ["rr"],
default: {
w: 640,
h: 640,
include: "*.png, *.jpg",
output: "collage.png",
rl: 2,
rr: false
},
});
if (args["mode"] === true) {
console.log(displayCollageModeType.join(", "));
Deno.exit(0);
}
const files: Set<string> = new Set();
const includeExtensions = Array.from(
String(args["include"]).matchAll(/\*\.([\w]+)/g),
).map(([_, group]) => group);
args["_"].forEach((arg) => {
arg = arg.toString();
if (Deno.statSync(arg).isDirectory) {
Array.from(
walkSync(arg, {
maxDepth: Infinity,
includeDirs: false,
includeFiles: true,
exts: includeExtensions.length ? includeExtensions : undefined,
}),
).forEach((entry) => files.add(entry.path));
} else {
files.add(arg);
}
});
if (files.size < 2) {
console.error("kollagen needs at least 2 images to work.");
Deno.exit(1);
}
const shuffledFiles = shuffle(Array.from(files));
const images: ProxyImage[] = shuffledFiles.map((file) => new ProxyImage(file));
const allModeKeys = args["mode"] ? parseDisplayCollageModes(args["mode"]) : displayCollageModeType;
const canvas = createCanvas(args["width"], args["height"]);
const context = canvas.getContext("2d");
const collageConfig: CollageConfig = {
numImages: args["n"],
};
const modeKey: DisplayCollageModeType = choice(allModeKeys);
if (modeKey === "recursive") {
console.log(
`Creating a recursive collage, choosing from ${shuffledFiles.length} files...`,
);
await denoCollageModes.recursiveDraw(context, images, {
modes: args["rm"] ? parseCollageModes(args["rm"]) : collageModeType,
repeat: args["rr"],
level: args["rl"],
});
} else {
const mode = denoCollageModes.modes[modeKey];
console.log(
`Creating a "${mode.name}" collage, choosing from ${shuffledFiles.length} files...`,
);
const segments = mode.getSegments(
context,
collageConfig,
images,
);
mode.place(context, images, segments);
console.log(`Used: ${images.slice(0, segments.length).map((img) => img.path).join(", ")}`)
}
const output = args["output"];
console.log(`Saving to "${output}"...`);
await Deno.writeFile(output, canvas.toBuffer());